如何在 Javascript 中使用循环生成事件处理程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6487366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate event handlers with loop in Javascript?
提问by Caballero
For example, I have 10 a tags generated from an AJAX response:
例如,我有 10 个从 AJAX 响应生成的标签:
<a href="#" id="b1">b1</a>
<a href="#" id="b2">b2</a>
<a href="#" id="b3">b3</a>
<a href="#" id="b4">b4</a>
<a href="#" id="b5">b5</a>
<a href="#" id="b6">b6</a>
<a href="#" id="b7">b7</a>
<a href="#" id="b8">b8</a>
<a href="#" id="b9">b9</a>
<a href="#" id="b10">b10</a>
I need to assign onclick event to each of them via loop:
我需要通过循环为每个人分配 onclick 事件:
for(i=1; i<11; i++) {
document.getElementById("b"+i).onclick=function() {
alert(i);
}
}
This doesn't work, it only assigns onclick to the last a tag and alerts "11". How can I get this to work? I'd prefer not to use jQuery.
这不起作用,它只将 onclick 分配给最后一个标签并警告“11”。我怎样才能让它工作?我不想使用 jQuery。
回答by SLaks
All of your handlers are sharing the same i
variable.
您的所有处理程序都共享相同的i
变量。
You need to put each handler into a separate function that takes i
as a parameter so that each one gets its own variable:
您需要将每个处理程序放入一个单独的函数中,该函数将其i
作为参数,以便每个处理程序都有自己的变量:
function handleElement(i) {
document.getElementById("b"+i).onclick=function() {
alert(i);
};
}
for(i=1; i<11; i++)
handleElement(i);
回答by Kevin
A closure is what you're looking for:
闭包就是你要找的:
for(i=1; i<11; i++) {
(function(i) {
document.getElementById("b"+i).onclick=function() {
alert(i);
};
})(i);
}
回答by Marisev
There are two ways to use closure on this problem. The idea is to create a scope with a snapshot of "i" variable for each iteration to be used by event handler.
有两种方法可以在这个问题上使用闭包。这个想法是为事件处理程序使用的每次迭代创建一个带有“i”变量快照的范围。
Solution #1 (as was mentioned by Kevin):
解决方案#1(正如凯文所提到的):
for(i=1; i<11; i++) {
(function(num) {
document.getElementById("b"+num).addEventListener('click', function() {
alert(num);
});
})(i);
}
Solution #2:
解决方案#2:
for (i=1; i<11; i++) {
document.getElementById("b"+i).addEventListener('click', (function(){
var num = i;
return function() {
alert(num);
}
})());
}