2013-08-03 21 views
0

我目前正在學習從下面的書籍的javascript數組「的JavaScript:好的部分 - O'Reilly Media公司」,它說以下內容:的Javascript閉包與節點

理解是很重要的內在功能訪問的外部函數的實際變量,而不是拷貝,以避免以下問題:

// BAD EXAMPLE 
// Make a function that assigns event handler functions to an array of nodes the 
wrong way. 
// When you click on a node, an alert box is supposed to display the ordinal of the 
node. 
// But it always displays the number of nodes instead. 
var add_the_handlers = function (nodes) 
{ 
    var i; 
    for (i = 0; i < nodes.length; i += 1) 
    { 
     nodes[i].onclick = function (e) 
     { 
      alert(i); 
     }; 
    } 
}; 
// END BAD EXAMPLE 

問:我不明白是什麼問題,如果有人能夠給我一份有編號的明顯例子並將大大讚賞的結果。

+0

[Javascript閉包內循環 - 簡單實用示例]的可能重複(http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) –

+0

無論您點擊哪個節點它會提醒相同的值,等於你通過的節點數。參見http://stackoverflow.com/questions/2568966/how-do-i-pass-the-value-not-the-reference js-variable-to-a-function和http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – DCoder

+0

@AnttiHaapala不錯!同樣的重複,幾秒鐘後,你沒有看到你的投票。 –

回答

0

這裏的問題是,您傳遞給onclick的函數會保留對每個循環中增加的相同i的引用。因此,當點擊被觸發時,我已經增加以匹配元素的數量。

2

每次循環遞增時,i的值都會更改,並且事件處理程序將會提示當前值i是什麼。所以如果有8個元素,當循環運行完成時,它們都會彈出7的值。

該示例的要點在於,許多人認爲,當每個處理程序最初與當前值i(例如0,1,2等)綁定時,它不會隨着i遞增而改變。這個例子證明事實並非如此,事件處理函數總是可以訪問當前值i,即使在綁定之後。