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

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

本文介绍了如何在JavaScript的HTML表格主体中插入行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an HTML table with a header and a footer:

<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中添加以下内容:

I am trying to add a row in tbody with the following:

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

,但该行已添加到tfoot部分.

but the row is added in the tfoot section.

如何插入tbody?

推荐答案

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

If you want to add a row into the tbody, get a reference to it and call its insertRow method.

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上为旧的演示)

(old demo on JSFiddle)

这篇关于如何在JavaScript的HTML表格主体中插入行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 22:00