停止事件冒泡 - 提高性能? [英] Stop event bubbling - increases performance?

查看:96
本文介绍了停止事件冒泡 - 提高性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我没有从事件回调中返回 false ,或者使用jQuery的 e.stopPropagation 功能,事件冒泡了DOM。

If I'm not returning false from an event callback, or using e.stopPropagation feature of jQuery, the event bubbles up the DOM.

在大多数情况下,我不关心事件是否起泡。与此DOM结构示例一样:

In most scenarios I don't care if the event bubbles or not. Like with this DOM structure example:

​<div id="theDiv">
    <form id="theForm" >
        <input type="submit" value="submit"/> 
    </form>
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

通常,我没有多个嵌套的提交回调,如下所示:

Normally, I don't have multiple nested submit callback like this:

$('#theDiv').submit(function() {
    alert('DIV!');
});
$('#theForm').submit(function(e) {
    alert('FORM!');
    e.preventDefault();
});​

小提琴

该DEMO将提交事件气泡显示为< div> ;

如果我停止传播或仅阻止默认,它对我没有区别。

Fiddle
That DEMO shows the submit event bubbles to a <div>!
It has no difference to me if I stop the Propagation or just prevent default.

在这些情况下,如果我停止传播,我会获得性能优势吗?

推荐答案

性能优势?是的,有一些轻微的好处,如 jQuery live()之间的性能测试所述 on() 。正如@Joseph所指出的那样,两者之间的区别在于,live会一直传播到树上,而 on()只会传递给最近的公共父。

Performance benefits? Yes, there are some slight benefits, as outlined in this performance test between jQuery live() and on(). As @Joseph also noted, the difference between the two is that live propagates all the way up the tree, while on() only goes to the nearest common parent.

在这些测试中,显示 on()可以胜过 live()最多4次。在实践中,这可能仍然不值得分裂,但如果你有非常深的html结构和大量的事件触发器,我认为停止传播的性能差异是值得的。

In those tests, it is shown that on() can outperform live() by up to 4 times. In practice, that's probably still not worth splitting hairs over, but if you have very deep html structures and lots of event triggers, the performance difference in stopping propagation can be worthwhile, I suppose.

这篇关于停止事件冒泡 - 提高性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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