I have this code:
var items = this.llistat.getElementsByTagName('a');
for( var i = 0; i < items.length; i++ ){
items[i].addEventListener('click', function(event) {
alert( i );
}, items[i]);
}
where the event is listened, but there are 3
items and the alert allways print 3
on any of the elements (it doesn't respect the index),
Dosen't items[i]
shouldn't do the job as closure?
thanks!
That's a classical closure issue : you must create a new function bound, not to the 'i' variable, but to its value at the time of binding :
No, the third argument of
addEventListener
is theuseCapture
one. See MDN for more information.But you can use:
or
The first one creates a new event handler for each element, so it needs more memory. The second one reuses the same event listener, but uses
indexOf
, so it's more slow.