解决javascript循环后 i 为固定值(循环的最后一项)

如果在循环中添加了等待触发事件(如click()),循环不会在执行过程等待事件触发,而是会直接完成数组的循环,最后的循环项 i 值会成为数组的长度

for(var i=0;i<tagN.length;i++){
    tagN[i].onclick=function(){
        console.log(i)  //输出 i 的最大值6
    }
}

如果希望可以在点击事件中获取以 i 为索引得志,可以在循环中为对象添加属性值,把 i 值赋给相应是标签对象

for(var i=0;i<tagN.length;i++){
    tagN[i].index=i;
    tagN[i].onclick=function(){
        console.log(this.index) //输出每个标签对应的索引值 i
    }
}

猜你喜欢

转载自blog.csdn.net/yuhui01/article/details/80814222