1

recently i was using js to add an event listener to all element that they have same class . for example "ones" and i wanted to have elements with different event listeners by just one function . I did somthing like this :

var ones = document.getElementsByClassName("one");
for (var i = 0; i < ones.length; i++) {
                ones[i].addEventListener('click',function(event){
     ale(i)});
                }
function ale(i){
 alert(i);
 }
I expect when i click on first element it show 1 ,second 2,and ... but when i click on every element (with class="ones") showed 7(length-1 of array) but when i was searching to solve this problem i got this answer:

var ones = document.getElementsByClassName("one");
for (var i = 0; i < ones.length; i++) {
 (function(i){
                ones[i].addEventListener('click',function(event){
     ale(i)});
 })(i)
                }
function ale(i){
 alert(i);
 }

but i cant understand why ? can someone help me ? Ienter code here heard this is a self-invoke function .what dose it mean?

Mahdi Nazari Ashani
  • 372
  • 1
  • 5
  • 22

0 Answers0