设置 onclick 以在循环中使用变量的当前值 [英] Setting onclick to use current value of variable in loop
问题描述
标题可能没有意义,单独的描述也没有意义,所以这里是代码示例:
The title may not make sense and nor would a description alone, so here's a sample of the code:
for(var a=0;a<10;a++) {
var b=document.createElement('b')
b.onclick=function() {
alert(a)
}
b.innerHTML=a
document.body.appendChild(b)
}
奇怪的是,当我将innerHTML 设置为a 时,它使用a 的当前值.因此,此代码创建了十个 元素,其值为 0、1、2、3、4、5、6、7、8、&9. 这完美地工作.然而,onclick 函数没有.当单击这些元素中的任何一个时,它返回
a
(10) 的最终值.我尝试将另一个变量设置为 a
,然后在 onclick 事件中使用该其他变量,但它仍然返回 a
的最终值.设置 onclick 时,如何让它使用 a
的值?
What's odd is that when I set innerHTML to a, it uses the current value of a. So, this code creates ten <b>
elements with the values 0, 1, 2, 3, 4, 5, 6, 7, 8, & 9. This works perfectly. What doesn't, however, is the onclick function. It returns the final value of a
(10) when any of these elements is clicked. I've tried setting another variable to a
and then using that other variable in the onclick event, but still it returns the final value of a
. How would I make it use the value of a
when onclick is set?
推荐答案
试试下面的
b.onclick= function(arg) {
return function() {
alert(arg);
}
}(a);
您遇到的问题是 javascript 不使用块作用域.相反,所有变量都有其包含函数的生命周期.所以在所有的 onclick
函数中只捕获了一个 a
并且他们都看到了它的最终值.
The problem you were hitting is that javascript doesn't use block scope. Instead all variables have a lifetime of their containing function. So there was only ever one a
captured in all of the onclick
functions and they all see it's final value.
解决方案通过为每个作用域创建一个新函数和值,然后立即将该值设置为 a
的当前值来解决此问题.
The solution works around this by creating a new function and value per scope and then immediately setting that value to the current value of a
.
这是一个稍微扩展的版本,可能更具可读性
Here's a version that's a bit expanded and perhaps a bit more readable
var createClickHandler = function(arg) {
return function() { alert(arg); };
}
for(var a=0;a<10;a++) {
var b=document.createElement('b')
b.onclick = createClickHandler(a);
b.innerHTML=a
document.body.appendChild(b)
}
这篇关于设置 onclick 以在循环中使用变量的当前值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!