2013-11-26 82 views
0

以下代碼是生成公告板列表。它適用於查看內容(例如,postId0,postId1,...),但工作就像'我'是nPostsJavaScript中循環的奇怪行爲

我記得在C#中我有同樣的問題,並通過聲明我的副本copy_i = i;在循環中),但是在這裏也沒有工作。

function loadList() { 
    $.getJSON("list.php", function (json) { 
     var nPosts = json.length; 
     for (var i = 0; i < nPosts; i++) { 
      var post = $('<ol/>', { 
       class: "viewPost", 
       id: "post" + i 
      }).appendTo("#viewList"); 

      $('<li/>', { 
       class: "viewPostId", 
       id: "postId" + i, 
       text: json[i].noteId 
      }).appendTo("#post" + i); 

      var memo = $('<li/>', { 
       class: "viewMemo", 
       id: "memo" + i, 
       text: json[i].noteContent 
      }).appendTo("#post" + i); 

      //alerts 'nPosts' for every i. 
      memo.on("click", function() { alert(i); }); 
     } 
    }); 
} 
+0

我通過讀碼了,但作爲一個初步的問題:你熟悉的概念關閉(以及計數器變量如何也可以關閉)?通常關於循環中的奇怪行爲的問題來自忽略閉包。 –

回答

2

正如預期的那樣我是執行的點擊功能,問題是有不可預見的關閉。這條線:

memo.on("click", function() { alert(i); }); 

創建在i變量,該變量遞增一路最大值您click處理程序調用過之前封閉。

這裏是你將如何提供一個「虛擬變量」爲您處理程序時可以關上:

var handlerCreator = function (counter) { 
    return function(){ 
     alert(counter); // The handler now closes over the counter variable, 
         // which cannot be accessed by other code and therefore 
         // retains the value passed in to this function (i.e. the 
         // value of i on the current iteration) 
    }; 
} 
memo.on("click", handlerCreator(i)); 
+0

謝謝!所以虛擬變量方法在js中不起作用,並且應該始終定義函數創建者。我認爲可能有一些更簡單的解決方法。 –

1

,提醒循環完成後,從而將等於nPosts