addEventListener,for(),index。如何使用闭包? [英] addEventListener, for(), index. how to use closure?

查看:204
本文介绍了addEventListener,for(),index。如何使用闭包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

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

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

事件被侦听,但是 3 项目和警报总是打印 3 在任何元素(它不尊重索引),

Dosen't items [i] 不应该作为关闭工作吗?



感谢!

解决方案

这是一个经典的关闭问题:您必须创建一个新的函数绑定,而不是'我'但绑定到它的价值:

  var items = this.llistat.getElementsByTagName('a'); 
$ b $ for(var i = 0; i< item.length; i ++){
items [i] .addEventListener('click',listener.bind(null,i));


函数侦听器(索引){
alert(index);
}


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!

解决方案

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);
}

这篇关于addEventListener,for(),index。如何使用闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆