如何在封闭外部作用域时取消引用 JavaScript 变量 [英] How can one de-reference JavaScript variables when enclosing an outer scope

查看:25
本文介绍了如何在封闭外部作用域时取消引用 JavaScript 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这是一个问题脚本.

Ok, here's a problem script.

var links = [ 'one', 'two', 'three' ];

for( var i = 0; i < links.length; i++ ) {
    var a = document.createElement( 'div' );
    a.innerHTML = links[i];
    a.onclick = function() { alert( i ) }
    document.body.appendChild( a );
}

此脚本使用数组生成三个 div:一、二和三.
我在每个 div 上设置了一个(为简单起见的 Dom0)点击处理程序,它会提醒它在数组中的位置索引.- 除了它没有!它总是提醒 3,即数组的最后一个索引.
这是因为 'alert( i )' 中的 'i' 是对外部作用域(在本例中为全局作用域)的实时引用,并且在循环结束时其值为 3.它需要的是一种在循环中取消引用 i 的方法.

This script generates three divs: one, two and three, using an array.
I've set a (Dom0 for simplicity) click handler on each div which alerts the index of its position in the array. - except it doesn't! It always alerts 3, the last index of the array.
This is because the 'i' in 'alert( i )' is a live reference to the outer scope (in this case global) and its value is 3 at the end of the loop. What it needs is a way of de-referencing i within the loop.

这是一种解决方案,我倾向于使用它.

This is one solution and I tend to use it.

var links = [ 'one', 'two', 'three' ];

for( var i = 0; i < links.length; i++ ) {
    var a = document.createElement( 'div' );
    a.innerHTML = links[i];
    a.i = i; //set a property of the current element with the current value of i
    a.onclick = function() { alert( this.i ) }
    document.body.appendChild( a );
}

还有其他人做不同的事情吗?
有没有真正聪明的方法?
有谁知道图书馆是如何做到这一点的?

Does anyone else do anything different?
Is there a really smart way of doing it?
Does anyone know how the libraries do this?

推荐答案

你需要使用这个闭包小技巧——创建并执行一个返回你的事件处理函数的函数.

You need to use this little closure trick - create and execute a function that returns your event handler function.

var links = [ 'one', 'two', 'three' ];

for( var i = 0; i < links.length; i++ ) {
    var a = document.createElement( 'div' );
    a.innerHTML = links[i];
    a.onclick = (function(i) { return function() { alert( i ) } })(i);
    document.body.appendChild( a );
}

这篇关于如何在封闭外部作用域时取消引用 JavaScript 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆