简体   繁体   English

数百个DOM元素的JavaScript事件监听器性能

[英]JavaScript event listener performance for hundreds of DOM elements

I have a <ul> that has many children (close to 3000 items) and some of the <li> s have many levels. 我有一个<ul> ,有很多孩子(接近3000项),有些<li>有很多级别。 I've attached an event listener on 'click' (I'm using jQuery) which I use to toggle the visibility of the children of an <li> . 我在'click'上附加了一个事件监听器(我正在使用jQuery),我用它来切换<li>子项的可见性。

I'm wondering how having so many event listeners impacts performance. 我想知道如此多的事件监听器会影响性能。 (There are at the very least 1000!). (至少有1000个!)。 Is this a big issue for performance? 这对性能来说是个大问题吗?

I'm not really seeing much of an issue performance wise with newer web browsers, but IE8 seems to be very slow. 对于较新的网络浏览器,我并没有真正看到很多性能问题,但IE8看起来非常慢。 Is it madly irresponsible to just whack an event listener on everything?! 在所有事情上敲打一个事件听众是不是不负责任?

The answer is a big whooping YES . 答案是一个很大的百日咳YES。 Yes, it will affect performance . 是的,它会影响性能 Event delegation was built for this exact thing. 事件委托是为这件事而建的。 Instead of binding your handler to every single li , bind it to its parent, the ul . 而不是将处理程序绑定到每个li ,而是将其绑定到其父级ul This way the ul will delegate the click event to li . 这样, ul会将click事件委托给li

$("ul").on("click", "li", function () {
 //your code
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM