Refactoring standard onClick
within html tag to listeners ,faced problem with my code:
var td;
for (var t=1;t<8;t++){
td = document.getElementById('td'+t);
if (typeof window.addEventListener==='function'){
td.addEventListener('click',function(){
console.log(td);
})}
}
When td
element is clicked on,it's assumed that clicked td
with last index from loop,e.g. 7
Looks like ,eventListeners
been populated for last element in this loop only.
Loop initialization looks correct.
Why so happened?
Here is live code
You need to wrap the assignment of the event listener in a closure, something like:
var td;
for (var t = 1; t < 8; t++){
td = document.getElementById('td'+t);
if (typeof window.addEventListener === 'function'){
(function (_td) {
td.addEventListener('click', function(){
console.log(_td);
});
})(td);
}
}