Saturday 25 November 2017

javascript - addEventListener, for(), index. how to use closure?






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!



Answer




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 :



var items =
this.llistat.getElementsByTagName('a');


for( var i = 0;
i < items.length; i++ ) {
items[i].addEventListener('click',
listener.bind( null, i) );
}

function listener(index)
{
alert(index);
}


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...