Attaching an event in a loop

what you do is bind the event to the class using the loop and index values ​​that are used in the code of the event handler. 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 I press any of the buttons, it warns

Clicked Button : 4

What could be the problem?

+3
source share
2 answers

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

I think you need 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 understandable

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);
}
+4
source

You need to close to commit changes i. As Lu said, this is due to the evaluation of the post.

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

All Articles