1

我有一个包含 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() 函数,整个循环工作正常,但是使用这个函数我得到了这个错误..

4

4 回答 4

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);

这是http://jsfiddle.net/Ex98V/上的一个运行示例

于 2013-02-14T13:17:04.427 回答
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];
}
于 2013-02-14T13:19:44.540 回答
0

k并在循环结束i读取(准确地说是 1 秒)。然后它们的值是 9 和 11,导致数组溢出问题。for

修复它的一种选择是创建一个完成工作的函数,并从kandi变量创建一个固定字符串来调用它:

function schreiben(__i, __k) {
   document.getElementById(''+__i+__k+'').value= Betrag[__i][__k];
}

然后setTimeout像这样调用:

setTimeout("schreiben("+i+","+k+")", 1000);

不是最优雅的方式,但它有效。

于 2013-02-14T12:50:51.293 回答
0

巴特弗里德里希斯是对​​的。不知道为什么要这样做,但是您可以在 schreiben 函数中声明几个 var 并在同一个 screiben 函数中递增它们。

于 2013-02-14T12:57:59.263 回答