我是prob。在這裏很密集,但我無法弄清楚下面的代碼到底發生了什麼。在for循環中創建閉包 - 我正在做這個對嗎?
我想要做的是將兩個單獨的處理程序附加到字段的更改事件。每個處理程序都是通過遍歷一個數組來設置的,並使用數組中的項來在處理程序運行時生成處理程序的輸出 - 希望在查看示例代碼時變得清晰。
代碼如下:
$(document).ready(function() {
//
// Create some test input fields on the page...
//
$('<br />').insertAfter($('body > *:last'));
$('<input type="text" name="t0" id="t0" value="" />').insertAfter($('body > *:last'));
$('<input type="text" name="t1" id="t1" value="" />').insertAfter($('body > *:last'));
//
// The problematic part - for me at least...
//
var arr = new Array(1, 2);
for (var a in arr) {
// Using Chrome console here for logging
console.log("## " + a);
$('#t0').change(function() {
console.log(">> " + a)
});
}
});
那麼,我希望當我的值添加到第一場出現的情況是,從控制檯(在Chrome瀏覽器上運行這些例子)中:
## 0
## 1
>> 1
>> 2
我得到的是:
## 0
## 1
>> 1
>> 1
我本來期望傳遞給處理函數會在a
的值上形成一個閉包,並且我將結束兩個函數綁定到處理程序,其中a
的值爲1
,其中a
的值爲2
。
想法?
乾杯 - 克里斯
快速提示:您不關閉文檔就緒功能。添加一個右括號')' – musefan 2012-02-22 17:53:38
瞭解JavaScript函數範圍將幫助您:http://stackoverflow.com/questions/7774636/jquery-event-handler-created-in-loop – paislee 2012-02-22 17:58:12
添加缺少')'@musefan - 謝謝 – Kris 2012-02-22 18:10:21