【问题标题】:Preserve HTML table location after dynamic update动态更新后保留 HTML 表格位置
【发布时间】:2021-04-03 22:50:58
【问题描述】:

当我使用appendChild() 更新 HTML 表格时,整个表格被移动到文档的底部。如何在 DOM 中保留表格的位置?

我的示例也发布在JSFiddle

<!--I want the existing table below to stay fixed in place after new rows are added.-->

<table id="table">
  <tr>
    <td> Table Cell 1</td>
    <td> Table Cell 2</td>
  </tr>
</table>

<!--The following button will add rows, but also move the table. How do I stop the move?-->

<input type="button" value="ADD NEW ROWS." onclick="generate_table()">

<script>
  // This function just creates new rows for the table 
  function generate_table() {
    var body = document.getElementsByTagName("body")[0];
    var tbl = document.getElementById("table");
    var tblBody = document.createElement("tbody");

    for (var i = 0; i < 2; i++) {
      var row = document.createElement("tr");
      for (var j = 0; j < 2; j++) {
        var cell = document.createElement("td");
        var cellText = document.createTextNode("cell " + i + ", column " + j);
        cell.appendChild(cellText);
        row.appendChild(cell);
      }
      tblBody.appendChild(row);
    }
    tbl.appendChild(tblBody);
    body.appendChild(tbl);
  }
</script>

<style>
  table,
  th,
  td {
    border: 1px solid black;
    border-collapse: collapse;
  }
</style>

【问题讨论】:

    标签: javascript html dom html-table


    【解决方案1】:

    删除以下行,你不需要它。

    body.appendChild(tbl);
    

    表格节点已经是文档对象模型的一部分,不需要再次添加。通过将元素附加到 body,您将其从当前位置移动到 body 节点的末尾。

    根据经验,您需要使用appendChild,前提是元素是使用createElement 动态创建的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-20
      • 2013-04-18
      • 2014-12-05
      • 2016-02-09
      • 2015-12-08
      • 2017-04-09
      • 2021-07-27
      相关资源
      最近更新 更多