+ 2

Event listener inside a loop

for (movie of movies) { const option = document.createElement('a'); const imgSrc = movie.Poster === 'N/A' ? '' : movie.Poster; option.innerHTML = ` <img src = "${imgSrc}"/> <p>${movie.Title}</p> `; option.addEventListener('click', () => { console.log(movie) }) dropDown.appendChild(option); } For each loop im creating a new arcor tag and adding it as option , Movie is sub objects of the object Movies , when im clicking a option i want the data of the movie object of the one option i clicked on , but when i click any option , the value of movie actually becomes the value of the last movie object inside movies

14th Aug 2021, 11:33 AM
Sabbir
Sabbir - avatar
2 Respostas
+ 1
I think event listener in a loop is not so gut idea. Maybe you can try in this way: option.addEventListener('change', e => { if(e.target.checked){ //do something } });
14th Aug 2021, 11:47 AM
JaScript
JaScript - avatar
+ 1
Sabbir This is because you implicitly declare movie as global variable, 'var' is implicit here: for(movie of movies) { ... } and when its global its unique and shared across all of your click event handlers. It gives the last item because thats where 'movie' ends up after the for loop. The easiest solution to avoid this is to declare it local with 'let' keyword: for(let movie of movies) { ... }
14th Aug 2021, 1:41 PM
Giorgos