Friday 28 October 2016

javascript - adding 'click' event listeners in loop




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


Answer



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);
}
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...