How to use closures to create event listeners in a Javascript for loop?

前端 未结 2 1293
深忆病人
深忆病人 2021-01-25 08:11

HTML

?
!
\"
&l         


        
2条回答
  •  粉色の甜心
    2021-01-25 09:15

    it doesn't work because

    charElems[i].addEventListener('mouseover',function() {
    
            (function(j) {mouseoverCheck(j);}(i));
    
        });
    

    addEventListener() is just assigning a handler and by the time that handler is called i will be 6.

    you should return a handler from an IIFE

    var charElems = document.getElementsByClassName('char');
    
      for (var i=0; i < charElems.length; i++) {
    
          charElems[i].addEventListener('mouseover', (function(temp) {
    
            return function(){
                 var j = temp;
                 //mouseoverCheck(j);
                 console.log(temp);
           }
        }(i)));
    } 
    

    Here is a fiddle: https://jsfiddle.net/qshnfv3q/

提交回复
热议问题