2013-07-26 65 views
0

下面的代碼始終返回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); 
} 
+0

搜索「在循環中創建處理程序的JavaScript」 –

回答

2

這是常見的。 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); 
} 

我會強烈建議您使用命名功能這不是時尚的內聯函數調用。它可能更有效,函數名稱提供有關函數目的的文檔。

1

你需要用單擊處理程序中關閉,創造i本地副本:

box.addEventListener("click", (function(i) { 
    return function() { 
    alert(array[i]); 
    } 
})(i), false); 

Fiddle

的方式你的代碼現在,i具有值爲3結束,而array[3]當然是不確定的。上述創建的i與值0,1 3份,2.

0

可能的最簡單的解決辦法是這樣的:

box.addEventListener("click", alert.bind(window, array[i]), false); 

但是,這將不是在IE <工作9.