停止事件冒泡-提高性能? [英] Stop event bubbling - increases performance?
问题描述
如果我没有从事件回调中返回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显示submit
事件冒泡到<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屋!