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

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

HTML

?
!
\"
&l         


        
相关标签:
2条回答
  • 2021-01-25 08:56
    var charElems = document.getElementsByClassName('char');
    
    for (var i = 0; i < charElems.length; i++) {
    
        //close...
        //charElems[i].addEventListener('mouseover',function() {
        //    (function(j) {mouseoverCheck(j);}(i));
        //});
    
        //like this
        (function(el, x) {
            el.addEventListener("mouseover", function() {
                mouseoverCheck(x);
            });
        })(charElems[i], i)
    
    
    }
    
    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题