addEventListener, for(), index. how to use closure? [duplicate]

谁说胖子不能爱 提交于 2020-01-12 07:10:34

问题


I have this code:

var items = this.llistat.getElementsByTagName('a');

for( var i = 0; i < items.length; i++ ){    
  items[i].addEventListener('click', function(event) {
    alert( i );
  }, items[i]);
}

where the event is listened, but there are 3 items and the alert allways print 3 on any of the elements (it doesn't respect the index),

Dosen't items[i] shouldn't do the job as closure?

thanks!


回答1:


That's a classical closure issue : you must create a new function bound, not to the 'i' variable, but to its value at the time of binding :

var items = this.llistat.getElementsByTagName('a');

for( var i = 0; i < items.length; i++ ) {
        items[i].addEventListener('click', listener.bind( null, i) );
}

function listener(index) {
         alert(index);
}



回答2:


No, the third argument of addEventListener is the useCapture one. See MDN for more information.

But you can use:

for( var i = 0; i < items.length; i++ ){
    (function(i){
        items[i].addEventListener('click', function(event) {
            alert( i );
        }, false);
    })(i);
}

or

var handler = function(event) {
    var i = items.indexOf(this);
    alert( i );
};
for( var i = 0; i < items.length; i++ ){
    items[i].addEventListener('click', handler, false);
}

The first one creates a new event handler for each element, so it needs more memory. The second one reuses the same event listener, but uses indexOf, so it's more slow.



来源:https://stackoverflow.com/questions/20587714/addeventlistener-for-index-how-to-use-closure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!