Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

javascript - JavaScript单击处理程序在for循环中没有按预期工作[duplicate](JavaScript click handler not working as expected inside a for loop [duplicate])

This question already has an answer here:

(这个问题在这里已有答案:)

I'm trying to learn JS and got an issue.

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

I tried many things and googled but all in vain.

(我尝试了很多东西并用Google搜索,但都是徒劳的。)

Following piece of code doesn't work as expected.

(下面的代码段不能按预期工作。)

I should get value of i on click but it always returns 6. I'm pulling my hair out., please help.

(我应该点击我的价值,但它总是返回6.我把我的头发拉出来,请帮忙。)

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

    console.log(i);

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

jsfiddle

(的jsfiddle)

  ask by JS-coder translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Working DEMO

(工作演示)

This is a classic JavaScript closure problem.

(这是一个典型的JavaScript闭包问题。)

Reference to the i object is being stored in the click handler closure, rather than the actual value of i .

(对i对象的引用存储在单击处理程序闭包中,而不是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.

(每个单击处理程序都将引用同一个对象,因为只有一个计数器对象可以容纳6,因此每次单击时会得到6个。)

The workaround is to wrap this in an anonymous function and pass i as argument.

(解决方法是将其包装在匿名函数中并将i作为参数传递。)

Primitives are copied by value in function calls.

(在函数调用中按值复制基元。)

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

UPDATE

(UPDATE)

Updated DEMO

(更新了DEMO)

Or you can use 'let' instead var to declare i .

(或者您可以使用'let'代替var来声明i 。)

let gives you fresh binding each time.

(let每次都给你新鲜的装订。)

It can only be used in ECMAScript 6 strict mode .

(它只能在ECMAScript 6 strict mode 。)

'use strict';

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...