扫码关注官方订阅号
触发click方法的时候k的取值总是heart_group.length+1,我想要每次绑定的时候k分别等于循环中的参数
for(k=0;k
闭关修行中......
其原因主要是,es5中没有块级作用域,整个循环结束后,k的值为length,可以通过下面三种方法解决
//法1——闭包 for (k = 0; k < heart_group.length; k++) { heart_group[k].addEventListener("click", (function(k) { return function() { clickHeart(k); } })(k), false); } //法2——bind方法 for (k = 0; k < heart_group.length; k++) { heart_group[k].addEventListener("click", function() { clickHeart(k); }.bind(heart_group[k]),false); } //法3——对象属性 for (k = 0; k < heart_group.length; k++) { heart_group[k].index = k; heart_group[k].addEventListener("click", function() { clickHeart(this.k); },false); }
k前面加let
for(let k=0;k<heart_group.length;k++){ heart_group[k].addEventListener("click",function(){ clickHeart(k); }); }
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
其原因主要是,es5中没有块级作用域,整个循环结束后,k的值为length,可以通过下面三种方法解决
k前面加let