如何在Javascript中的HTML表体中插入行? [英] How to insert row in HTML table body in Javascript?

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

问题描述

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

 < table id =myTable> 
< thead>
< tr>
< th>我的标题< / th>
< / tr>
< / thead>
< tbody>
< tr>
< td> aaaaa< / td>
< / tr>
< / tbody>
< tfoot>
< tr>
< td>我的页脚< / td>
< / tr>
< tfoot>
< / table>

我试图在 tbody 与以下内容:

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

但该行添加在 tfoot 部分。

如何插入 tbody

解决方案

如果你想添加一行到 tbody 中,获取它的引用并将其添加到那里。

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

//在最后一行的表中插入一行
var newRow = tableRef.insertRow(tableRef.rows.length);

//在索引0处插入一个单元格
var newCell = newRow.insertCell(0);

//将文本节点追加到单元格
var newText = document.createTextNode('New row');
newCell.appendChild(newText);

一份工作演示此处
您也可以查看 insertRow 这里


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>

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

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

but the row is added in the tfoot section.

How to insert it tbody?

解决方案

If you want to add a row into the tbody, get a reference to it and add it there.

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

// Insert a row in the table at the last row
var newRow   = tableRef.insertRow(tableRef.rows.length);

// Insert a cell in the row at index 0
var newCell  = newRow.insertCell(0);

// Append a text node to the cell
var newText  = document.createTextNode('New row');
newCell.appendChild(newText);

A working demo here. Also you can check the documentation of insertRow here.

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

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