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

人走茶凉 提交于 2019-12-13 05:05:32

问题


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.


回答1:


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);



回答2:


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);
}



回答3:


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);
        }
    })());
}


来源:https://stackoverflow.com/questions/25067809/submit-variables-into-a-loop-of-ajax-calls

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!