javascript - JavaScript 中循环的奇怪行为

标签 javascript for-loop closures

下面的代码是生成公告板列表。它可以很好地查看内容(例如,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/

相关文章:

javascript - Angular:FileReader - 读取器执行次数过多

javascript - 为什么在 TypeScript 中使用三等号 (===)?

java - 重复函数的时间呈指数增加

rust - 将非复制变量移动到异步闭包 : captured variable cannot escape `FnMut` closure body

JavaScript 闭包问题

javascript - 从列表中显示不同的弹出窗口。

javascript - jQuery 在父元素上切换 onclick

C++ for循环奇怪的行为

c - 需要解释奇数 for 循环/作用域问题

ios - 调用将 UIViewController 插入闭包内部的函数,就好像它在外面一样