问题描述
我在我的JavaScript代码中使用了委托事件处理程序(jQuery),所以当单击动态添加的按钮时,就会发生事情.
I am using a delegated event handler (jQuery) in my JavaScript code so stuff happens when dynamically added buttons are clicked.
我想知道这样做是否存在性能缺陷?
I'm wondering are there performance drawbacks to this?
// Delegated event handler
$(document).on('click', '#dynamicallyAddedButton', function(){
console.log("Hello");
});
与性能相比,它会如何呢?
How would it compare to this, performance-wise?
// Regular event handler
$("#regularButton").on('click', function(){
console.log("Hello Again");
});
查看 jQuery文档,看来事件总是会冒泡DOM树的方式.这是否意味着元素嵌套得越深,事件生效所需的时间就越长?
Looking at the jQuery documentation, it seems that events always bubble all the way up the DOM tree. Does that mean that the further nested an element is, the longer an event will take to work?
是否存在使用JavaScript的事件委托而不是jQuery可以提高性能?在问类似的问题,那里的答案很有用.我想知道使用常规事件处理程序和委托事件处理程序之间有什么区别.链接的问题使事件看起来像是不断冒泡的DOM树.使用委托的事件处理程序,事件是否会冒泡到顶部,然后又回落到指定的元素?
Is there a performance benefit to using JavaScript's event delegation rather than jQuery's? is asking a similar question, and the answer there is useful. I am wondering what the difference is between using a regular event handler and a delegated event handler. The linked questions make it seem like events are constantly bubbling up the DOM tree. With a delegated event handler does the event bubble up to the top and then back down to the specified element?
推荐答案
每次您在文档中的几乎任何位置单击时,事件都会手动弹出到document
元素(自然冒泡发生后),并且将运行单击的元素和document
之间的每个元素的选择器引擎.
Every time you click pretty much anywhere in the document, the event is going to be manually bubbled up to the document
element (after the natural bubbling takes place) and will run the selector engine for every element between the clicked element and the document
.
因此,如果您单击嵌套20个元素深的元素,则选择器引擎将为该单击运行20次.
So if you click on an element nested 20 elements deep, the selector engine will run 20 times for that one click.
此外,document
具有的每个选择器都将发生这种情况.因此,如果为它提供20个选择器并单击20个深的元素,则选择器引擎必须为该一次单击运行400次. (当然,手动冒泡仅发生一次.)
Furthermore, this will happen for every selector the document
has. So if you give it 20 selectors and click 20 elements deep, the selector engine has to run 400 times for that one click. (The manual bubbling happens only once, of course.)
基于选择器的委派很好,但是请尽可能使它与目标元素更接近.
Selector-based delegation is fine, but try to keep it closer to the targeted element(s) if possible.
这篇关于在JavaScript和jQuery中使用委托事件处理程序是否存在性能缺陷?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!