for循环中的多个不同事件侦听器
问题描述:
下面的代码始终返回undefined。为什么是这样?我希望事件侦听器使用索引的字符串进行响应。for循环中的多个不同事件侦听器
感谢
var array = ["Hey", "Hi", "Hello"];
for (var i = 0; i < array.length; i++) {
var box = document.createElement("div");
box.className = "box";
box.addEventListener("click", function() {
alert(array[i]);
}, false);
}
答
这是常见的。 JavaScript没有块范围。变量作用域仅在调用函数时创建。因此,要将您的i
范围限定为当前循环迭代,您需要在也会创建处理程序的函数调用中引用它。
// Create a function that returns a function
function createHandler(i) {
// The value of `i` is local to this variable scope
// Return your handler function, which accesses the scoped `i` variable
return function() {
alert(array[i]);
}
}
var array = ["Hey", "Hi", "Hello"];
for (var i = 0; i < array.length; i++) {
var box = document.createElement("div");
box.className = "box";
// Invoke the `createHandler`, and pass it the value that needs to be scoped.
// The returned function will use its reference to the scoped `i` value.
box.addEventListener("click", createHandler(i), false);
}
我会强烈建议您使用命名功能这不是时尚的内联函数调用。它可能更有效,函数名称提供有关函数目的的文档。
答
你需要用单击处理程序中关闭,创造i
本地副本:
box.addEventListener("click", (function(i) {
return function() {
alert(array[i]);
}
})(i), false);
的方式你的代码现在,i
具有值为3结束,而array[3]
当然是不确定的。上述创建的i
与值0,1 3份,2.
答
可能的最简单的解决办法是这样的:
box.addEventListener("click", alert.bind(window, array[i]), false);
但是,这将不是在IE <工作9.
搜索“在循环中创建处理程序的JavaScript” –