jQuery 替换表格数据而不是追加

3

我有一段jQuery代码,可以在具有tbody id manifest_table的表格中追加一些行。

$.each(order_data, function(i, item) {
    $('<tr>').html("<td>" + order_data[i][0] + "</td><td>" + order_data[i][1]  + "</td><td>" + order_data[i][2]  + "</td><td>" + order_data[i][3]  + "</td>").appendTo('#manifest_table');
});

<table id="manifest_table" data-toggle="table" data-search="true" data-show-refresh="true" data-show-toggle="true" data-show-columns="true" data-sort-name="dispatch_by_date" data-page-list="[50, 100]" data-page-size="50" data-pagination="true">
    <thead>
        <tr>
            <th data-align="center" data-sortable="true">Order Item ID</th>
            <th data-align="center" data-sortable="true">Channel</th>
            <th data-align="center" data-sortable="true">Courier</th>
            <th data-align="center" data-sortable="true">Tracking</th>
        </tr>
    </thead>
    <tbody id="manifest_table">
    </tbody>
</table>

我想知道如何替换整个表格的内容而不是追加它?

2
在tbody上使用.html()方法。 - Jai
最好保留您的循环,并在循环附加之前清除 tbody。只需在开头添加 $('#manifest_table').html('');,或者如果我没记错的话,您可以直接使用 $('#manifest_table').empty(); - musefan
1个回答

4

看起来你正在进行循环。因此,在开始循环之前,请先清空:

$('#manifest_table').empty();   // or
$('#manifest_table').html('');  // use this, any one of the two
$.each(order_data, function(i, item) {
    $('<tr>').html("<td>" + order_data[i][0] + "</td><td>" + order_data[i][1]  + "</td><td>" + order_data[i][2]  + "</td><td>" + order_data[i][3]  + "</td>").appendTo('#manifest_table');
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接