Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  52] [ 2]  / answers: 1 / hits: 47814  / 13 Years ago, wed, january 18, 2012, 12:00:00

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


More From » events

 Answers
3

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

[#87946] Tuesday, January 17, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
keyonnaelled

Total Points: 35
Total Questions: 113
Total Answers: 99

Location: South Korea
Member since Fri, Sep 11, 2020
4 Years ago
;