Javascript For-Loop后没有任何事情发生

时间:2014-03-19 00:24:38

标签: javascript jquery

我在Javascript中有一个完美执行的for循环,但在}循环的结束for之后没有任何内容执行,例如alert("before");addListener()函数!

function deleteRow(rowNum){
    var tablelinks = document.getElementById("table1").rows.length;
    //deletes that row number called
    document.getElementById("table1").deleteRow(rowNum);
    //reorders the row numbers in the delete links to reflect their new position
    for(var i = 0; i < tablelinks; i++) {   
        document.getElementById("table1").rows[i].cells[8].innerHTML = '<a href="#" onclick="deleteRow(' + i + ')">Del</a>';
    }

    //these things below do not work
    alert("before");    
    addListener()
    alert("after");             
    sumrows()
}

1 个答案:

答案 0 :(得分:4)

因为您在删除目标行之前正在读取行长度

function deleteRow(rowNum) {
    document.getElementById("table1").deleteRow(rowNum); //deletes that row number called
    var tablelinks = document.getElementById("table1").rows.length;
    for (var i = 0; i < tablelinks; i++) { //reorders the row numbers in the delete links to reflect their new position
        document.getElementById("table1").rows[i].cells[8].innerHTML = '<a href="#" onclick="deleteRow(' + i + ')">Del</a>';
    }
    alert("before");
    addListener()
    alert("after");
    sumrows()
}

演示:Fiddle

假设您有5行而您正在删除第3行,则tablelinks变为5,但在下一行中您将删除第3行,现在您只有4行。现在,当循环i变为4时,document.getElementById("table1").rows[i]语句将返回undefined,因为rows只有4个元素而不是5。


您可以通过将链接引用而不是行数传递给删除方法(如

)来进一步简化它
<td><a href="#" onclick="deleteRow(this)">Del</a></td>

然后

function deleteRow(link) {
    document.getElementById("table1").deleteRow(link.parentNode.parentNode.rowIndex); //deletes that row number called
    alert("before");
    addListener()
    alert("after");
    sumrows()
}

演示:Fiddle