设置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的当前值。因此,此代码创建了10个< b>
元素,其值为0,1,2,3,4,5,6,7,8和&这完美无缺。然而,onclick功能不是什么。当单击任何这些元素时,它返回 a
(10)的最终值。我已经尝试将另一个变量设置为 a
然后在onclick事件中使用该另一个变量,但它仍然返回的最终值
。当设置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 $来解决此问题。 C $ C>。
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屋!