首页 > 解决方案 > 在javascript中每次调用刷新行

问题描述

我正在用 HTML 构建一个表格。

使用 JavaScript,我根据数组中对象的数量附加了一些表行,然后附加单元格。效果很好,这里是代码:

function Build_table(filtered_data){
  filtered_data.forEach((obj => {
    // Create table rows for each object
    var row = tbody.append("tr");
    Object.entries(obj).forEach(function(x){
        // Create cell within current row.
        var cell = row.append("td");
        // give cell a value
        cell.text(x[1]);
    });
  })
);
<thead>
  <tr>
    <th class="table-head">Date</th>
    <th class="table-head">City</th>
    <th class="table-head">State</th>
    <th class="table-head">Country</th>
    <th class="table-head">Shape</th>
    <th class="table-head">Duration</th>
    <th class="table-head">Comments</th>
  </tr>
</thead>
<tbody></tbody>

但问题是当我第二次输入搜索时,之前的搜索结果仍然存在。如何每次使用纯 Javascript 刷新?

标签: javascripthtml

解决方案


在这种情况下,您需要先清理表格主体的 html,例如:

document.getElementsByTagName("tbody")[0].innerHTML='';

然后是您的旧程序:

filtered_data.forEach((obj => {
    // Create table rows for each object
    var row = tbody.append("tr");
    Object.entries(obj).forEach(function(x){
        // Create cell within current row.
        var cell = row.append("td");
        // give cell a value
        cell.text(x[1]);
    });
}));

推荐阅读