Wednesday, March 27, 2019

How to generate event handlers with loop in Javascript?




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



b1
b2
b3
b4
b5
b6

b7
b8
b9
b10


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.


Answer



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


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...