如何在 JavaScript 中的 HTML 表体中插入一行

新手上路,请多包涵

我有一个带有页眉和页脚的 HTML 表格:

 <table id="myTable">
    <thead>
        <tr>
            <th>My Header</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>aaaaa</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td>My footer</td>
        </tr>
    <tfoot>
</table>

我正在尝试在 tbody 添加一行,内容如下:

 myTable.insertRow(myTable.rows.length - 1);

但该行已添加到 tfoot 部分。

如何插入 tbody

原文由 Jérôme Verstrynge 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 478
2 个回答

如果要在 tbody 中添加一行,请获取对它的引用并调用其 insertRow 方法。

 var tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

// Insert a row at the end of table
var newRow = tbodyRef.insertRow();

// Insert a cell at the end of the row
var newCell = newRow.insertCell();

// Append a text node to the cell
var newText = document.createTextNode('new row');
newCell.appendChild(newText);
 <table id="myTable">
  <thead>
    <tr>
      <th>My Header</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>initial row</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>My Footer</td>
    </tr>
  </tfoot>
</table>

(JSFiddle 上的旧 演示

原文由 Jonathan Naguin 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 jQuery 尝试以下片段:

 $(table).find('tbody').append("<tr><td>aaaa</td></tr>");

原文由 Sasidharan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题