JavaScript click handler not working as expected inside a for loop [duplicate]

2020/10/11 22:00 · javascript ·  · 0评论

我正在尝试学习JS并遇到问题。

我尝试了许多事情,然后用谷歌搜索,但都徒劳无功。遵循下面的代码无法按预期工作。我应该在点击时获得i的值,但它总是返回6。我正在拔头发,请帮助。

for (var i = 1; i < 6; i++) {

    console.log(i);

    $("#div" + i).click(
        function() {
            alert(i);
        }
    );
}

jsfiddle

Working DEMO

This is a classic JavaScript closure problem. Reference to the i object is being stored in the click handler closure, rather than the actual value of i.

Every single click handler will refer to the same object because there’s only one counter object which holds 6 so you get six on each click.

解决方法是将其包装在匿名函数中,然后将i作为参数传递。在函数调用中按值复制基元。

for(var i=1; i<6; i++) {
     (function (i) {
        $("#div" + i).click(
            function () { alert(i); }
        );
     })(i);
}

更新

更新了演示

或者你可以使用“让”,而不是var申报ilet每次都为您提供新鲜的绑定。它只能在ECMAScript 6中使用strict mode

'use strict';

for(let i=1; i<6; i++) {

        $("#div" + i).click(
            function () { alert(i); }
        );
 }

问题在于,当您遍历循环时,i它会增加。它的最终值为6。当您说alert(i)要让javascript告诉您单击链接时,i多少,此时该值为6。

如果要获取包装箱中的物品,则可以执行以下操作:

for (var i = 1; i < 6; i++) {

    console.log(i);

    $("#div" + i).click(function(e) {
        alert($(this).text());
    });
}

工作示例:http : //jsfiddle.net/rmXcF/2/

$("#div" + i).click(
    function() {
        alert(i);
    }
);

It's because it's using the value of i as a closure. i is remembered through a closure which increases at every stage of the foor loop.

$("#div" + i).click(function(event) {
    alert($(event.target).attr("id").replace(/div/g, ""));
});
本文地址:http://javascript.askforanswer.com/javascript-click-handler-not-working-as-expected-inside-a-for-loop-duplicate.html
文章标签: ,   ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!