问题描述
以下代码始终返回undefined。为什么是这样?我希望事件监听器使用索引的字符串进行响应。
The code below always returns undefined. Why is this? I want the event listener to respond with the string of the index.
谢谢
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
范围扩展到当前循环迭代,您需要在也创建处理程序的函数调用中引用它。
This is asked frequently. JavaScript doesn't have block scope. Variable scope is only created when you invoke a function. So to scope your i
to the current loop iteration, you need to reference it in a function invocation that also creates the handler.
// 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 would strongly encourage you to use named functions for this instead of the trendy inline function invocations. It's potentially more efficient, and the function name provides documentation as to the purpose of the function.
这篇关于for循环中有多个不同的事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!