If, for example, I have series of event listeners created like this:
如果,例如,我有一系列事件监听器创建如下:
var els = document.getElementyById('myList').getElementsByTagName('li');
for (i=0;i<els.length;i++) {
els[i].addEventListener(eventType, function(e){ /* do stuff */ }, true);
}
First off, am I committing some kind of heresy like this? I mean, is there a faaar simpler way of doing this other than an event for each <li>
element?
首先,我是在做这样的异端邪说吗?我的意思是,除了每个
In either case, the main question is: what happens to those event listeners if the <li>
s are removed/replaced? What would happen if I did this:
在这两种情况下,主要的问题是:如果
document.getElementyById('myList').innerHTML = 'Hello World!';
Do the listeners stay 'suspended' thus slowing down the browser (assume I have a lot of <li>
s), or are they automatically removed? Is it even an issue?
监听器是否会停留在“暂停”状态,从而减慢浏览器的速度(假设我有很多
1 个解决方案
#1
3
Event handlers assigned to destroyed elements are marked for garbage collection. Meaning they are removed from memory. Also, if every one of your events does the same thing, bind them to the encompassing <ul>
- click events will bubble up from the li
s to the ul
.
分配给销毁元素的事件处理程序标记为垃圾收集。意味着它们被从记忆中移除。另外,如果每个事件都做相同的事情,那么将它们绑定到包含的
-
- click事件将会从lis到ul。
Also,
同时,
"is there a faaar simpler way of doing this other than an event for each
<li>
element?"“除了每个
元素的事件外,还有什么faaar更简单的方法来做这件事吗?” 元素的事件外,还有什么faaar更简单的方法来做这件事吗?” Using a delegated handler attached to the containing ul element makes sense here. Not necessarily simpler, but only slightly more complicated and more efficient - or maybe it is simpler if you are dynamically adding li elements. And it completely avoids the issue you are worried about.
使用一个委托的处理程序附加到包含的ul元素上是有意义的。不一定更简单,但只是稍微复杂一点,更高效——或者,如果动态添加li元素,可能会更简单。它完全避免了你所担心的问题。
(Courtesy of @nnnnnn)
(由@nnnnnn)
Converted comment to answer as it seems to have helped answer the question.
这似乎有助于回答这个问题。
#1
3
Event handlers assigned to destroyed elements are marked for garbage collection. Meaning they are removed from memory. Also, if every one of your events does the same thing, bind them to the encompassing <ul>
- click events will bubble up from the li
s to the ul
.
分配给销毁元素的事件处理程序标记为垃圾收集。意味着它们被从记忆中移除。另外,如果每个事件都做相同的事情,那么将它们绑定到包含的
-
- click事件将会从lis到ul。
Also,
同时,
"is there a faaar simpler way of doing this other than an event for each
<li>
element?"“除了每个
元素的事件外,还有什么faaar更简单的方法来做这件事吗?” 元素的事件外,还有什么faaar更简单的方法来做这件事吗?” Using a delegated handler attached to the containing ul element makes sense here. Not necessarily simpler, but only slightly more complicated and more efficient - or maybe it is simpler if you are dynamically adding li elements. And it completely avoids the issue you are worried about.
使用一个委托的处理程序附加到包含的ul元素上是有意义的。不一定更简单,但只是稍微复杂一点,更高效——或者,如果动态添加li元素,可能会更简单。它完全避免了你所担心的问题。
(Courtesy of @nnnnnn)
(由@nnnnnn)
Converted comment to answer as it seems to have helped answer the question.
这似乎有助于回答这个问题。