这段代码困扰了我一整天。假设 ledCount = 9,代码通过 ID 获取元素没有任何问题,但由于它必须绑定(bind)一个单独的函数 onClick,并且由于变量 i 是本地变量,因此 writeLED 函数始终获取第一个参数 10(即 max i+1),但它需要获取当前的 i+1,就像 getElementBy id i+1 所做的那样。有谁能解开这个谜题吗?
function showLED(ledCount){
for(var i = 0;i<=(ledCount-1);i++){
if(color[i] == 0){
document.getElementById('buttonLED'+(i+1)).onclick = function(){writeLED((i+1),1); } ;
document.getElementById('buttonLED'+(i+1)).value="light is on";
}else{
document.getElementById('buttonLED'+(i+1)).onclick = function(){writeLED((i+1),0); } ;
document.getElementById('buttonLED'+(i+1)).value="light is off";
}
}
}
最佳答案
您需要将其包装在一个自执行函数中以创建一个新作用域,您可以在其中保留递增函数的当前值。
您可以像这样内联执行此操作:
document.getElementById('buttonLED'+(i+1)).onclick = function(loopincrement){
return function(){writeLED((loopincrement+1),1); } ;
}(i)
或者作为像这样的拉出函数:
function writeLEDInNewScope(inc){
return function(){ writeLED(inc,1)};
}
document.getElementById('buttonLED'+(i+1)).onclick = writeLEDinNewScope(i+1);
外部函数将为内部 onclick 函数保留 i 值的当前值。它立即执行并返回您想要绑定(bind)到 onclick 属性的内部函数。它将维护对 loopincrement
变量的引用,该引用不会受到 future 循环迭代的影响。
关于Javascript - 在函数中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15316197/