Maison > Questions et réponses > le corps du texte
问题可能一句话描述不清楚,先给出代码,大家可以建立一个html文档运行一下:
for (var i = 0; i < 10; i++) {
var b=document.createElement("button")
b.textContent=i
b.onclick=function (e){
alert("this is "+i)
}
document.body.appendChild(b)
}
我想实现的效果是,点5号按钮,弹出对话框就显示this is 5。当然现在无论点击几号按钮都出现this is 10。原因我清楚,但是不知道怎么修改才行。求助各位大大!
大家讲道理2017-04-10 12:48:07
尽量不要用闭包,闭包有性能问题.
for (var i = 0; i < 10; i++) {
var b = document.createElement("button");
b.index=i;
b.textContent = i;
b.onclick = function(){
alert("this is "+this.index);
};
document.body.appendChild(b);
}
天蓬老师2017-04-10 12:48:07
把i
作为参数传过去就可以了:
for (var i = 0; i < 10; i++) {
var b = document.createElement("button");
b.textContent = i;
b.onclick = (function(i){
return function(e){
alert("this is " + i);
}
})(i);
document.body.appendChild(b);
}
阿神2017-04-10 12:48:07
很奇怪,以下方式居然也不行: for (var i = 0; i < 10; i++) { var b=document.createElement("button"); b.innerText=i; b.onclick=function (e){ alert("this is "+b.innerText); } document.body.appendChild(b); }