首页 > 解决方案 > Jquery 删除使用 .after 创建的元素

问题描述

我的 html 文件中有一个表,其中列标题是硬编码的:

<table id="debugger-table">
    <tr>
        <th>Attribute</th>
        <th>Computed</th>
        <th>Correct</th>
    </tr>
</table>

我使用 jquery 在 .js 文件中填充第 2 行以后的值:

tableString = '';

DEBUG_DATA.forEach(function(debug_line){
    tableString += '<tr><td>' + debug_line['attribute'] + '</td><td>' + debug_line['computed'] + '</td><td>' + debug_line['correct'] + '</td>'
});

$('#debugger-table tr:last').after(tableString);

当用户执行某个操作时,我想更新这些值。我的问题是如何删除我添加的文本,以便我可以用新文本替换它,而不仅仅是在旧值之后附加新值。

我想我可以销毁整个表,然后使用列标题创建一个新表。不过似乎有点矫枉过正。有没有办法引用 .after 添加的文本并将其删除?谢谢。

标签: javascripthtmljquery

解决方案


将添加存储到 jQuery 对象中:

const rows = $(tableString);
('#debugger-table').append(rows); // Tip: this is better than
                                  // $('#debugger-table tr:last').after(rows);

然后在需要时将其删除:

rows.remove();

推荐阅读