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

标签 javascript html html-table insert row

我有一个带有页眉和页脚的 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

最佳答案

如果你想在 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 上的旧 demo)

关于javascript - 如何在 JavaScript 中的 HTML 表体中插入一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18333427/

相关文章:

javascript - 根据选择选项显示 div?

javascript - 如何比较文本与数组元素?

javascript - 简单的Javascript-HTML5音频,在结束前20秒调用函数

java - 用 Java 向服务器请求表

html - 如何在表格中换行同时具有不同的单元格宽度?

php - 如何让 "th "只出现一次

javascript - Facebook "Invalid redirect_uri",但 url 对我来说看起来不错

javascript - 删除本地存储

html - 如何将 : I would like to have several rectangles (box? ) 自动调整为浏览器的高度

html - 用两个盒子简单响应?