HTMLTableElement: insertRow() 方法
HTMLTableElement 接口的 insertRow() 方法会在给定的 <table> 中插入一个新的行 (<tr>),并返回新行的引用。
如果一个表格有多个 <tbody> 元素,默认情况下,新行会被插入到最后一个 <tbody> 中。要将行插入到特定部分,请使用 HTMLTableSectionElement.insertRow()。
注意: insertRow() 直接将行插入到表格中。无需像使用 Document.createElement() 创建新的 <tr> 元素那样单独追加该行。
语法
js
insertRow()
insertRow(index)
HTMLTableElement 是对 HTML <table> 元素的引用。
参数
index可选-
新行的行索引。如果
index为-1或等于行数,则该行将被追加为最后一行。如果省略index,则默认为-1。
返回值
一个引用新行的 HTMLTableRowElement。
异常
IndexSizeErrorDOMException-
如果
index大于行数,则抛出异常。
示例
此示例使用 insertRow(-1) 将新行追加到表格中。
然后,我们使用 HTMLTableRowElement.insertCell() 在新行中插入一个新单元格。(为了使 HTML 有效,<tr> 必须至少有一个 <td> 元素。)最后,我们使用 Document.createTextNode() 和 Node.appendChild() 向单元格添加一些文本。
HTML
html
<table id="my-table">
<tr>
<td>Row 1</td>
</tr>
<tr>
<td>Row 2</td>
</tr>
<tr>
<td>Row 3</td>
</tr>
</table>
JavaScript
js
function addRow(tableID) {
// Get a reference to the table
let tableRef = document.getElementById(tableID);
// Insert a row at the end of the table
let newRow = tableRef.insertRow(-1);
// Insert a cell in the row at index 0
let newCell = newRow.insertCell(0);
// Append a text node to the cell
let newText = document.createTextNode("New bottom row");
newCell.appendChild(newText);
}
// Call addRow() with the table's ID
addRow("my-table");
结果
规范
| 规范 |
|---|
| HTML # dom-table-insertrow-dev |
浏览器兼容性
加载中…