闭包的本质是作用域链,我们在工作中常常无意间就会创建一个闭包,比方:

<input type="button" ></input>
<input type="button" ></input>
<input type="button" ></input>
<input type="button" ></input>
<input type="button" ></input>
<input type="button" ></input>
<input type="button" ></input>
<input type="button" ></input>
<input type="button" ></input>
<input type="button" ></input>
<script type="text/javascript">
for (var i = 1; i <= 10; i++)
{
   document.getElementById("id"+i).onclick = function () 
    {
        alert(i);
    }
}
</script>

执行之后,会发现每一个onclick时间执行时弹出的都是11!

这是由于,onclick 函数是在 全局作用域里面被定义的,被定义的时候。会生成一个对象。这个对象继承了当前运行环境的作用域链。也就是说。这个函数运行体里的 i 。引用的是全局作用域里的i。

由于 for 循环运行完以后,全局作用域下的 i 的值变为了 11,所以才会每一个onclick函数都弹出11。

为了解决问题,我们须要为每一个 onclick 函数的生成建立一个单独的作用域。然后 onclick 函数弹出这个作用域里面的 局部变量:

<input type="button" ></input>
<input type="button" ></input>
<input type="button" ></input>
<input type="button" ></input>
<input type="button" ></input>
<input type="button" ></input>
<input type="button" ></input>
<input type="button" ></input>
<input type="button" ></input>
<input type="button" ></input>
<script type="text/javascript">
for (var i = 1; i <= 10; i++)
{
    (function () {
        var m;
        m = i;
        document.getElementById("id"+m).onclick = function () 
        {
            alert(m);
        }
    })();
}
</script>


相关文章:

  • 2021-06-24
  • 2022-02-04
  • 2021-10-31
  • 2022-12-23
  • 2022-12-23
  • 2021-07-02
  • 2022-01-19
  • 2021-10-24
猜你喜欢
  • 2022-12-23
  • 2021-08-24
  • 2022-12-23
  • 2022-01-02
  • 2022-12-23
  • 2022-12-23
  • 2022-01-24
相关资源
相似解决方案