+ 6
Event Listener inside a For Loop
I am working on a web app and I need to handle many event listeners on an array of divs at the same time. Is there any way to do that inside a for loop because in my code the event listener is not working properly. The following is a sample of my code : //arr is an array of div elements for(var i = 0;i<10;i++){ arr[i].addEventListener(âclickâ,function(){ //code }) }
11 Respostas
+ 11
The logic is fine. I remember doing something similar in JS. We'll have to look at what arr stores and if al the objects are relevant when you attach the event listeners.
It would be good if you can link your full code, or the error message which comes with it (if any).
+ 7
I would suggest to add the event to one parent element of the divs than to all the divs. This approach will significantly increase the performance.
Here is the example without the for loop and only using single event listner:
https://code.sololearn.com/Ww7TS0vDx0Z5/?ref=app
+ 5
It might be good, if you included your code! Let me know if you wanna do the 'Same Work' with all of those Event Listeners! Like Biraj 's code shows !
+ 3
Hatsy Rei
No error occured during the execution of my program. It is just that the click event listeners did not work.
My code is similar to Birajâs code
but i noticed that in his code he used for(let i =0... instead of for(var i=0... so i changed it and now the problem is solved but I donât know why đ
Thank you for your great responses đ·...
+ 3
Would be better if your post your code.....
+ 2
https://code.sololearn.com/WcrK9q8wYrAa/?ref=app
round about line 100
0
The problem is now solved
Here is a demonstration on how it works
https://code.sololearn.com/WfiGShUfT29w/?ref=app