search

Home  >  Q&A  >  body text

Javascript的onclick函数调用外部变量的上下文能保存么?

问题可能一句话描述不清楚,先给出代码,大家可以建立一个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。原因我清楚,但是不知道怎么修改才行。求助各位大大!

ringa_leeringa_lee2896 days ago606

reply all(5)I'll reply

  • 大家讲道理

    大家讲道理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);
    }
    
    

    reply
    0
  • 天蓬老师

    天蓬老师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);
    }
    

    reply
    0
  • 阿神

    阿神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); }

    reply
    0
  • 黄舟

    黄舟2017-04-10 12:48:07

    我也遇到这样的问题 在使用raphel 一款jquery ui时遇到的 LZ如果解决了 希望分享一下

    reply
    0
  • PHP中文网

    PHP中文网2017-04-10 12:48:07

    把 for 中的 var 改成 let 就行。

    reply
    0
  • Cancelreply