下面的代码是生成公告板列表。它可以很好地查看内容(例如,postId0,postId1,...),但工作方式就好像“i”是nPosts
我记得在 C# 中我遇到了同样的问题,并通过声明 i 的副本(var 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); });
}
});
}
最佳答案
正如预期的那样,问题出在意外的关闭上。这一行:
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));
关于javascript - JavaScript 中循环的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20208035/