javascript中的反向事件冒泡 [英] Reverse event bubbling in javascript

查看:358
本文介绍了javascript中的反向事件冒泡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您知道,事件通常会在javascript中冒泡,因此触发事件的元素的事件处理程序将首先执行,然后调用父元素的事件处理程序,依此类推.此行为在我当前正在处理的项目上引起了一些问题,我希望执行顺序相反.

As you know, events usually bubble up in javascript, so the event handler of the element that fires the event is executed first, then the event handler of the parent element is called and so on. This behaviour causes some problems on a project I'm currently working on, I would rather have the execution order reversed.

我想出了一个使用超时的解决方案:

I figuered out a solution that is using timeouts:

$(element).mouseover(function(){
    var that = this;
    setTimeout(function() {
       //actual event handler, but references to "this" are replaced with "that"
    },$(this).parents().length)
 });

因此,基本上,事件处理程序是在短暂的超时后执行的,等待时间取决于DOM树中元素的深度: html-element的事件处理程序将立即执行,body元素的事件处理程序将在等待1毫秒后执行,依此类推.因此,事件的执行顺序是相反的.

So basically, the event handlers are executed after a short timeout, the waiting time depends on the the depth of the element in the DOM-tree: The event handler of the the html-element is executed right away, the event handler of the body element is executed after waiting 1ms and so on. So the execution order of the events is reversed.

我的第一个测试结果是肯定的,但是我仍然不确定该解决方案是否存在任何问题或缺点.您如何看待该解决方案?对于如何解决此问题的其他想法也受到高度赞赏.

The results of my first tests are positive, but I'm still not sure if there are any problems or drawbacks with this solution. What do you think of this solution? Other ideas on how to solve this problems are also highly appreciated.

推荐答案

反向事件冒泡称为捕获阶段.

Reverse event bubbling is called capture phase.

请参见 DOM事件体系结构

true作为第三个参数传递给Event.addEventListener,以使其在捕获阶段触发

Pass true as the 3rd argument to Event.addEventListener to have it trigger on capture phase

el.addEventListener("click", function () {
  console.log("i run in capture");
}, true);

当然,它不能在旧版平台上运行.您将需要DOM3事件填充程序来模拟事件系统.随时为 DOM-shim

Of course it won't work in legacy platforms. You'll need a DOM3 events shim to emulate the event system. Feel free to contribute to the DOM-shim

这篇关于javascript中的反向事件冒泡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆