我有一个带有页眉和页脚的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
发布于 2013-08-20 19:20:16
如果要向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 )
发布于 2013-08-20 19:13:21
您可以使用jQuery尝试以下代码片段
$(table).find('tbody').append("<tr><td>aaaa</td></tr>");
发布于 2017-12-09 04:02:19
基本方法:
这将添加HTML格式的内容并显示新添加的行。
var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;
https://stackoverflow.com/questions/18333427
复制相似问题