Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching event in loop

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

Whenever I click any of the buttons, it alerts:

Clicked Button : 4

What could be the problem?

like image 817
Sourabh Avatar asked Jun 11 '26 00:06

Sourabh


1 Answers

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);
}
like image 156
Lou Franco Avatar answered Jun 13 '26 16:06

Lou Franco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!