The title seems like a piece of cake, but that is not exactly what I am trying to ask. I just can't think of a better title, if you have any after reading the following, please comment and I will update the title.
With jQuery, it is quite easy to do this, because click()
passes this
parameter,
$('img').click(function(){console.log($(this).attr('id')})
I was trying to do this using vanilla javascript, and encountered some pitfall
imgs = document.getElementsByTagName('img');
l = imgs.length;
for (i=0;i<l;i++) {
imgs[i].addEventListener('click',function(){console.log(imgs[i].id)});
}
This won't work because every listner will be trying to console.log(imgs[l].id)
.
I have worked out a workaround:
imgs = document.getElementsByTagName('img');
l = imgs.length;
listener_generator = function(id){
var s = function(){
console.log(id);
};
return s;
};
for (i=0;i<l;i++) {
imgs[i].addEventListener('click',listener_generator(imgs[i].id));
}
For learning purpose, I kind of remember when I read some javascript book, besides the approach above, there are other ways to do this, but I can't find it now. My question is, is there any other way to do this? And which one is the best practice?