attaching event in loop

蓝咒 提交于 2019-12-10 21:19:26

问题


what am doing is attaching event on a class using a loop and index values are being used in the event handler code. here is my code:

var classElements=document.getElementsByClassName("a");
for(var i=0; i<4; i++)
{
    classElements[i].onClick=function(){
       alert("Clicked button : "+i);
    }
}

when ever I click any of the buttons, it alerts

Clicked Button : 4

What could be the prob?


回答1:


JavaScript closes over the object and evaluates it later when it is called. At the time it is called, i is 4.

I think you want something like:

var classElements=document.getElementsByClassName("a");
for(var i=0; i<4; i++)
{
    classElements[i].onClick=function(j) { 
       return function(){
          alert("Clicked button : "+j);
       };
    }(i);
}

EDIT: shown with named functions to make the code more clear

var classElements=document.getElementsByClassName("a");
for(var i=0; i<4; i++)
{
    var makeFn = function(j) { 
       return function(){
          alert("Clicked button : "+j);
       };
    };
    classElements[i].onClick = makeFn(i);
}



回答2:


You need a closure in order to capture the changes of i. As Lou stated this is due to post evaluation.

var classElements=document.getElementsByClassName("a");
for(var i=0; i<4; i++)
    classElements[i].onclick = (function(i){
          return function(){ alert("Clicked button : " + i) }; 
       })(i);


来源:https://stackoverflow.com/questions/10389021/attaching-event-in-loop

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