How to generate event handlers with loop in Javascript? [duplicate]
Solution 1:
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);
Solution 2:
A closure is what you're looking for:
for(i=1; i<11; i++) {
(function(i) {
document.getElementById("b"+i).onclick=function() {
alert(i);
};
})(i);
}