我得到了一张包含8x10单元格的表。。每个销售都有一个带有自己id的输入元素(11,12,…,21,22,23,…)现在我想在之后(比如0.5秒)填充这些输入我刚输入了一些测试的值
Betrag = new Array();
Betrag[0] = new Array();
Betrag[1] = new Array("asd","asd","asd","asd","asd","asd","asd","asd","asd","asd","513.000,00");
Betrag[2] = new Array("asd","adsd","asd","asd","asd","asd","asd","asd","asd","asd","asd");
Betrag[3] = new Array("asd","asd","asd","asd","asd","asd","asd","asd","asd","asd","asd");
Betrag[4] = new Array("asd","uisgui","asd","asd","asd","asd","asd","asd","asd","asd","asd");
Betrag[5] = new Array("asd","asd","asd","asd","asd","asd","asd","asd","asd","asd","asd");
Betrag[6] = new Array("asd","asd","asd","asd","asd","asd","asd","asd","asd","asd","asd");
Betrag[7] = new Array("asd","asd","asd","asd","asd","asd","asd","asd","asd","asd","asd");
Betrag[8] = new Array("asd","asd","asd","asd","asd","asd","asd","asd","asd","asd","asd");
for(i=1; i<=8; i++){
for(k=1; k<=10; k++){
setTimeout(function schreiben(){document.getElementById(''+i+k+'').value= Betrag[i][k];}, 1000);
//document.getElementById(''+i+k+'').value= Betrag[i][k];
}
}
编译器说"TypeError:无法读取未定义的属性"11"
如果我不使用settimeout()函数,整个循环都可以正常工作,但使用此函数时我犯了这个错误。。
您可以尝试以下操作:
var i = 1;
var k = 1;
var obj = setInterval( function () {
document.getElementById(i + '' + k).value= Betrag[i][k];
if(k <= 10)
k++;
else
{
k = 1;
if(i<=8)
i++;
else
clearInterval(obj);
}
}, 1000);
以下是上的运行示例http://jsfiddle.net/Ex98V/
这应该按照您想要的方式工作。
for(i=1; i<=8; i++){
for(k=1; k<=10; k++){
(function(i, k){
setTimeout(function schreiben(){document.getElementById(''+i+k+'').value= Betrag[i][k];}, 1000*k + 10000*i);
//document.getElementById(''+i+k+'').value= Betrag[i][k];
})(i, k);
}
}
为了让事情变得更清楚,可以考虑这样的重构:
for(i=1; i<=8; i++){
for(k=1; k<=10; k++){
setSchreibTimeout(i, k);
}
}
function setSchreibTimeout(i, k){
setTimeout(function schreiben(){document.getElementById(''+i+k+'').value= Betrag[i][k];}, 1000*k + 10000*i);
//document.getElementById(''+i+k+'').value= Betrag[i][k];
}
k
和i
在for
循环结束后读取(准确地说是1秒)。它们的值分别为9和11,从而导致数组溢出问题。
修复它的一个选项是创建一个完成工作的函数,并从k
和i
变量创建一个固定字符串来调用它:
function schreiben(__i, __k) {
document.getElementById(''+__i+__k+'').value= Betrag[__i][__k];
}
然后这样调用setTimeout
:
setTimeout("schreiben("+i+","+k+")", 1000);
不是最优雅的方式,但它很有效。