通过javascript渲染html表格

问题描述 投票:0回答:1

我陷入了一个奇怪的点......

// ticketList refers to an html table id
console.log("ticketList.rows.length before: " + ticketList.rows.length);
    for (i= 1; i < ticketList.rows.length; i++) {
        ticketList.rows[i].remove();
        console.log(`ticket ${i - 1} removed`);
    }

    // some more code which works properly

    console.log("ticketList.rows.length after: " + ticketList.rows.length);

现在这是控制台输出:

ticketList.rows.length before: 13
ticket 0 removed
ticket 1 removed
ticket 2 removed
ticket 3 removed
ticket 4 removed
ticket 5 removed
ticketList.rows.length after: 19

初始值13是正确的。 为什么它在 6 次迭代后停止,而不是像想象的那样删除 12 个元素?

我尝试在 for 循环中对停止值进行硬编码,但出现以下错误:

无法读取未定义的属性(读取“删除”)

javascript html-table
1个回答
0
投票

如果删除一行,您的索引将关闭。最简单的解决方案是向后迭代。

for (let i = ticketList.rows.length - 1; i >= 0; i--) {
    ticketList.rows[i].remove();
    console.log(`ticket ${i - 1} removed`);
}

另请注意,这是删除所有行,如果您想保留第一行,只需使用

i > 0
;

参见拼接未按我预期的方式工作

© www.soinside.com 2019 - 2024. All rights reserved.