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

前端 未结 2 1290
深忆病人
深忆病人 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)
    
    
    }
    

提交回复
热议问题