2012-12-04 40 views
0

可能重複裏面工作:
Javascript: closure of loop?jQuery也不太for循環

我有以下里面的javascript代碼:

for (var i=0; i < images_array.length; i++) { 
$('#thumb_'+ i).live('click', function(){ 
    $('#image_container_' + current_image_index).hide(); 
    current_image_index = i; 
    alert(current_image_index); 
    $('#image_container_' + current_image_index).show(); 
});} 

當我點擊任何拇指,我得到了images_array.length值。有誰知道發生了什麼事?

+1

您的'i'變量存儲在本地關閉中。您需要添加另一個具有「i」本地副本的功能級別。 –

+0

這個問題已經被無數次的回答了,因此我一直沒有搜索 – jAndy

+1

恐怕只有在瞭解解決方案後才能輕鬆搜索。如果不理解關閉的想法,很難有什麼想法去搜索...... –

回答

1

你需要創建一個封閉的點擊處理函數,就像這樣:

for (var i=0; i < images_array.length; i++) { 
    $('#thumb_'+ i).live('click', 
     (function(i) { 
      return function(){ 
       $('#image_container_' + current_image_index).hide(); 
       current_image_index = i; 
       alert(current_image_index); 
       $('#image_container_' + current_image_index).show(); 
      } 
     })(i) 
    ); 
} 

的問題是,如果沒有關閉,該變量跨越每一個處理函數共享 - 它繼續得到更新,這就是爲什麼每個處理程序最終都會獲得array.length值。使用閉包創建變量i的本地範圍副本。

這裏有一個演示,顯示了區別:

+0

哦,其實我找到了另一種方式,但我會將你標記爲答案,謝謝你的幫助 – user1801180

0
$.each(images_array,function(value,i) { 
    $('#thumb_'+ i).live('click', function(){ 
    $('#image_container_' + current_image_index).hide(); 
    current_image_index = i; 
    alert(current_image_index); 
    $('#image_container_' + current_image_index).show(); 
});} 

正如其他人所說,你需要關閉。現在,你已經在使用jQuery,所以忘了for()並直接使用$ .each。