如何在封闭外部作用域时取消引用JavaScript变量 [英] How can one de-reference JavaScript variables when enclosing an outer scope
问题描述
好的,这是一个问题脚本。
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为简单)click处理程序,它会提醒它在数组中的位置索引。 - 除了没有!它总是警告3,即数组的最后一个索引。
这是因为'alert(i)'中的'i'是外部作用域的实时引用(在本例中为global)及其值在循环结束时是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屋!