开发者

How to generate event handlers with loop in Javascript? [duplicate]

This question a开发者_C百科lready has answers here: Javascript infamous Loop issue? [duplicate] (5 answers) Closed 7 years ago.

For example, I have 10 a tags generated from an AJAX response:

<a href="#" id="b1">b1</a>
<a href="#" id="b2">b2</a>
<a href="#" id="b3">b3</a>
<a href="#" id="b4">b4</a>
<a href="#" id="b5">b5</a>
<a href="#" id="b6">b6</a>
<a href="#" id="b7">b7</a>
<a href="#" id="b8">b8</a>
<a href="#" id="b9">b9</a>
<a href="#" id="b10">b10</a>

I need to assign onclick event to each of them via loop:

for(i=1; i<11; i++) {
    document.getElementById("b"+i).onclick=function() {
        alert(i);
    }
}

This doesn't work, it only assigns onclick to the last a tag and alerts "11". How can I get this to work? I'd prefer not to use jQuery.


All of your handlers are sharing the same i variable.

You need to put each handler into a separate function that takes i as a parameter so that each one gets its own variable:

function handleElement(i) {
    document.getElementById("b"+i).onclick=function() {
        alert(i);
    };
}

for(i=1; i<11; i++) 
    handleElement(i);


A closure is what you're looking for:

for(i=1; i<11; i++) {
    (function(i) {
        document.getElementById("b"+i).onclick=function() {
            alert(i);
        };
    })(i);
}


There are two ways to use closure on this problem. The idea is to create a scope with a snapshot of "i" variable for each iteration to be used by event handler.

Solution #1 (as was mentioned by Kevin):

for(i=1; i<11; i++) {
    (function(num) {

       document.getElementById("b"+num).addEventListener('click', function() {
            alert(num);
       });

    })(i);
}

Solution #2:

for (i=1; i<11; i++) {
    document.getElementById("b"+i).addEventListener('click', (function(){
        var num = i;
        return function() {
            alert(num);
        }
    })());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜