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