将事件添加到新节点 [英] Add events to new nodes
问题描述
我一直在尝试使用for循环将点击
事件添加到一系列 divs
中。 divs
是动态创建和加载的。每个div都应该调用自己的回调函数。但似乎每个div都附加到最终事件监听器并调用最终事件监听器的回调函数。
I have been trying to add click
events to a series of divs
using a for loop. The divs
are dynamically created and loaded. Every div is supposed to call its own callback function. But it seems every div is attached to the final event listener and calls callback function of final event listener.
以下是我的基本代码:
for(index=0; index<divs.length; index++) {
divs[index].addEventListener("click", function(){console.log(divs[index].getAttribute("id"));}, true); //capture click event
}
点击后,只显示最终div的id每个div。
On click only the id of final div is displayed by every div.
推荐答案
Phil的回答为您发布的特定代码(+1)提供了一个很好的解决方案,但没有解释原始代码的问题。
Phil's answer offers a good solution to the specific code you posted (+1), but doesn't explain what the problem was with your original code.
问题是事件处理程序闭包得到持久引用到索引
变量,而不是副本它们的创建时间。所以他们都看到 index
的最终值( divs.length
)。例如,此代码
The problem is that the event handler closures get an enduring reference to the index
variable, not a copy of it as of when they're created. So they all see the final value that index
has (divs.length
). For instance, this code
for (index = 0; index < 4; ++index) {
setTimeout(function() {
console.log(index);
}, 100);
}
...超时时会记录4四次,而不是0,1,2和3。
...will log "4" four times when the timeouts occur, not "0", "1", "2", and "3".
要在确保处理程序关闭的一般情况下更正它特定值,使用为您生成事件处理函数的工厂函数,其中事件处理程序关闭您提供工厂函数而不是循环变量的参数:
To correct it in the general case where you want to make sure your handler closes over a specific value, use a factory function that generates the event handler function for you, where the event handler closes over the argument you feed the factory function instead of the loop variable:
for(index=0; index<divs.length; index++) {
divs[index].addEventListener("click", createHandler(divs[index], true); //capture click event
}
function createHandler(div) {
return function(){
console.log(div.getAttribute("id"));
};
}
在那里,事件处理程序关闭 div
,它不会改变。
There, the event handler closes over div
, which doesn't change.
闭包是JavaScript最强大的功能之一。一旦你理解它们是如何工作的(而且他们实际上是一个比人们想象的要简单得多,你可以用它们来达到很好的效果。更多: 闭包不复杂
Closures are one of the most powerful features of JavaScript. Once you understand how they work (and they're actually a lot simpler than people think), you can use them to really good effect. More: Closures are not complicated
这篇关于将事件添加到新节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!