使用反射属性的 JavaScript 事件不返回,看不到数组的其余部分
在 IE 中使用 JavaScript,我使用了反射属性,但问题是我有 12 个项目,并且全部为警报 12
。
当我使用setAttribute
时,没有问题。
到目前为止我所拥有的:
var items = [1,2,3,4,5,6,7,8,9,10,11,12];
for (i in items) {
newdiv = document.createElement("div");
//newdiv.setAttribute("class","box");
//newdiv.setAttribute("id",items[i]);
//newdiv.setAttribute("ondblclick","chkItem("+items[i]+");");
newdiv.className = "box";
newdiv.id = items[i];
newdiv.ondblclick = function() {alert(items[i])}
newdiv.innerHTML = " " + items[i];
document.getElementById("items").appendChild(newdiv);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更改:
对此:
查找 Closures,这就是让你陷入困境的原因这个案例。当您使用
function() { }
创建匿名函数时,您正在创建一个绑定在其创建范围内的闭包。因此,在闭包中,变量 i 与循环中使用的变量相同。因此,当您双击某个项目时,循环已经完成并且i == 12
。这与直接在for(i in items) { }
循环之后放置alert(i);
是一样的。那么,考虑到这一点,我的第二个例子如何解决这个问题?
嗯,它使用一个自动执行的匿名函数,该函数接受一个变量
item
。该函数返回一个闭包,该闭包绑定在其范围内。外部闭包会立即执行,传入items[i]
,这会为您想要驻留的变量创建一个稳定的作用域。如果您不习惯,闭包可能会有点令人费解。但理解它们是使用 JavaScript 进行函数式编程的重要组成部分。
SetAttribute 之所以有效,是因为您正在创建一个新字符串,该字符串每次通过循环都会进行计算,而不是延迟引用变量
i
。PS
在数组上使用
for( in ) {}
可能是个坏主意。您可能会得到意想不到的结果,它应该循环遍历对象的所有属性,而不仅仅是数组中的项目。使用常规for(var i=0;i 可能更安全
change:
to this:
Look up Closures, which is what is screwing you up in this case. When you create an anonymous function using
function() { }
, you are creating a closure that is bound in the scope that it was created. So inside your closure, your variablei
is the same variable that you were using in the loop. So when you double click on an item, the loop is already finished andi == 12
. It would be the same as if you put analert(i);
directly after yourfor(i in items) { }
loop.So, with that in mind, how does my second example fix that?
Well, it uses a self-executing anonymous function that accepts one variable,
item
. This function returns a closure, which is bound inside its scope. The outer closure is immediately executed, passing initems[i]
, which creates a stable scope for the variable that you want to live in.Closures can be a little mind bending if you aren't used to them, but understanding them is a big part to getting functional programming using JavaScript.
SetAttribute works because you are creating a new string that evaluates each time through the loop, rather than late-referencing the variable
i
.PS
Its probably a bad idea to use a
for( in ) {}
on an array. You might get unexpected results, it should loop through all the propertys of the object not just the items in the array. its probably safer to use a regularfor(var i=0;i<items.length;i++) {}
因为在双击的函数调用中,您正在引用已经为其定义了 ID 值的元素...为什么不直接使用。
其中
this
是 newdiv 元素。示例
Because within the function call for double click you are referencing the element which you have already defined an ID value for... why not just use.
Where
this
is the newdiv element.Example Here