I read that one can use closures for addEventListener in loops (addEventListener using for loop and passing values).
However, this method does not work with a more complex example:
function f(fevent) {
var a = document.createElement('a');
a.innerHTML = 'Test';
a.href = '#';
a.addEventListener('click', fevent);
return a;
};
for (l = 0; l < 2; l += 1) {
for (h = 0; h < 2; h += 1) {
document.body.appendChild(
f(function() {alert(l+','+h);})
);
}
}
https://jsfiddle.net/yasnujzq/
Edit: I want is that the click event on the anchors to alert different combinations (0,0), (1,0), (0,1), and (1,1). But it always alerts (2,2).
Here is what I tried with the closure method from above:
function f(fevent) {
var a = document.createElement('a');
a.innerHTML = 'Test';
a.href = '#';
a.addEventListener('click', fevent);
return a;
};
for (l = 0; l < 2; l += 1) {
for (h = 0; h < 2; h += 1) {
(function() {
document.body.appendChild(
f(function() {alert(l+','+h);})
);
}());
}
https://jsfiddle.net/72sg8d5n/
I also tried to add arguments to the closure:
function f(fevent) {
var a = document.createElement('a');
a.innerHTML = 'Test';
a.href = '#';
a.addEventListener('click', fevent);
return a;
};
for (l = 0; l < 2; l += 1) {
for (h = 0; h < 2; h += 1) {
(function() {
document.body.appendChild(
f(function() {alert(l+','+h);})
);
}(l,h));
}
}
https://jsfiddle.net/wxodr8p6/
Maybe someone can enlighten me on this.
Edit: Here is a working fiddle with the method from the accepted solution below: