在给相似元素循环绑定事件时,结果所有元素返回的结果相同,例如:
var fragment=document.createElement("fragment");
for(var i=0;i<10;i++){
var button=document.createElement("button");
button.onclick=function(){
console.log(i);
};
button.innerHTML=i;
fragment.appendChild(button);
}
document.body.appendChild(fragment);
由于i是全局变量,在执行完for循环后i=10。每个console.log(i)中的i都是全局变量中的i,所以每次事件触发时都会去全局作用域中找i,所以每个按钮打印的都是10。
可以使用以下方法来解决该问题:
方法一:使用闭包
var fragment=document.createElement("fragment");
for(var i=0;i<10;i++){
var button=document.createElement("button");
button.onclick=(function fun(i){
return function(){console.log(i);};
})(i);
button.innerHTML=i;
fragment.appendChild(button);
}
document.body.appendChild(fragment);
此时console.log(i)中的i是外层函数fun的局部作用域中的i,每次执行fun时都会创建一个新的作用域,所以每个i都是不同作用域上的局部变量,所以每个i都不相同。又因为产生了闭包所以每个变量i,在执行完for循环后依然存在。
方法二:在ECMA6中使用let
var fragment=document.createElement("fragment");
for(let i=0;i<10;i++){
var button=document.createElement("button");
button.onclick=function(){
console.log(i);
}
button.innerHTML=i;
fragment.appendChild(button);
}
document.body.appendChild(fragment);
此时i是不同块级作用域中的局部变量,每个i都不相同,所以打印出来的也不相同。