How To Generate Event Handlers With Loop In Javascript?
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:
functionhandleElement(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);
}
Solution 3:
There are two ways to use closure on this problem. The idea is to create a scope with a snapshot of "i" variable for each iteration to be used by event handler.
Solution #1 (as was mentioned by Kevin):
for(i=1; i<11; i++) {
(function(num) {
document.getElementById("b"+num).addEventListener('click', function() {
alert(num);
});
})(i);
}
Solution #2:
for (i=1; i<11; i++) {
document.getElementById("b"+i).addEventListener('click', (function(){
var num = i;
returnfunction() {
alert(num);
}
})());
}
Post a Comment for "How To Generate Event Handlers With Loop In Javascript?"