Reputation: 2623
What am I essentially trying to do is to produce container with buttons, which have the same handler but get different arguments like this:
<div id="container">
<button onclick="onclick_handler(1)">1</button>
<button onclick="onclick_handler(2)">2</button>
<button onclick="onclick_handler(3)">3</button>
</div>
Using this:
function onload_handler() {
var container = document.getElementById("container");
var i;
for (i = 0; i < 3; i++) {
var button = document.createElement('button');
button.innerHTML = i;
button.addEventListener('click', function() {
onclick_handler(i);
});
container.appendChild(button);
}
}
function onclik_handler(val) {
console.log(val);
}
And when I click buttons I get 4 in my console. What am I doing wrong?
Could it also be done without usage of anonymous functions?
Upvotes: 3
Views: 42
Reputation: 67217
Try to resolve the problem created by closure, by creating a scope per iteration,
function(i){
button.addEventListener('click', function() {
onclick_handler(i);
});
})(i);
And your full code would be,
function onload_handler() {
var container = document.getElementById("container");
var i;
for (i = 0; i < 3; i++) {
var button = document.createElement('button');
button.innerHTML = i;
(function(i){
button.addEventListener('click', function() {
onclick_handler(i);
});
})(i)
container.appendChild(button);
}
}
function onclik_handler(val) {
console.log(val);
}
Upvotes: 3