猿问

addEventListener 绑定的方法传入参数不对

触发click方法的时候k的取值总是heart_group.length+1,我想要每次绑定的时候k分别等于循环中的参数

 for(k=0;k<heart_group.length;k++){

                heart_group[k].addEventListener("click",function(){                                        

                    clickHeart(k);

                });


芜湖不芜
浏览 794回答 1
1回答

胡说叔叔

其原因主要是,es5中没有块级作用域,整个循环结束后,k的值为length,可以通过下面三种方法解决//法1——闭包for (k = 0; k < heart_group.length; k++) {&nbsp; &nbsp; heart_group[k].addEventListener("click", (function(k) {&nbsp; &nbsp; &nbsp; &nbsp; return function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; clickHeart(k);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })(k), false);}//法2——bind方法for (k = 0; k < heart_group.length; k++) {&nbsp; &nbsp; heart_group[k].addEventListener("click", function() {&nbsp; &nbsp; &nbsp; &nbsp; clickHeart(k);&nbsp; &nbsp; }.bind(heart_group[k]),false);}//法3——对象属性for (k = 0; k < heart_group.length; k++) {&nbsp; &nbsp; heart_group[k].index = k;&nbsp; &nbsp; heart_group[k].addEventListener("click", function() {&nbsp; &nbsp; &nbsp; &nbsp; clickHeart(this.k);&nbsp; &nbsp; },false);}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答