我有一个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()函数,整个循环工作正常,但是这个函数我犯了这个错误..
答案 0 :(得分:2)
您可以尝试这样的事情:
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);
的示例
答案 1 :(得分:2)
这应该按照你想要的方式工作。
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];
}
答案 2 :(得分:0)
k
和i
在<{strong> for
循环结束后读取(确切地说是1秒)。它们的值为9和11,导致阵列溢出问题。
修复它的一个选项是创建一个完成工作的函数,并从k
和i
变量创建一个固定字符串来调用它:
function schreiben(__i, __k) {
document.getElementById(''+__i+__k+'').value= Betrag[__i][__k];
}
然后像这样调用setTimeout
:
setTimeout("schreiben("+i+","+k+")", 1000);
不是最优雅的方式,但它有效。
答案 3 :(得分:0)