Wednesday 27 March 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...