這是常見的。 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);
}
我會強烈建議您使用命名功能這不是時尚的內聯函數調用。它可能更有效,函數名稱提供有關函數目的的文檔。
搜索「在循環中創建處理程序的JavaScript」 –