如何在 JavaScript 中的 HTML 表格正文中插入一行 [英] How to insert a row in an HTML table body in JavaScript

查看:10
本文介绍了如何在 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 表格正文中插入一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆