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