HTMLTableRowElement: insertCell() 方法
HTMLTableRowElement 接口的 insertCell() 方法用于在表格行()中插入一个新的单元格(<tr>),并返回对该单元格的引用。<td>
注意: insertCell() 会直接将单元格插入到行中。该单元格不需要像使用 创建新的 Document.createElement()<td> 元素时那样,单独使用 来追加。Node.appendChild()
不过,你不能使用 insertCell() 来创建新的 <th> 元素。
语法
js
insertCell()
insertCell(index)
参数
index可选-
新单元格的索引。如果
index为-1或等于单元格的数量,则单元格将作为行的最后一个单元格被追加。如果省略index,则默认为-1。
返回值
一个 ,引用新单元格。HTMLTableCellElement
异常
IndexSizeErrorDOMException-
如果
index大于单元格的数量,则会抛出此异常。
示例
此示例使用 HTMLTableRowElement.insertCell() 将一个新单元格追加到行中。
HTML
html
<table>
<thead>
<tr>
<th>C1</th>
<th>C2</th>
<th>C3</th>
<th>C4</th>
<th>C5</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
</tbody>
</table>
<button id="add">Add a cell</button>
<button id="remove">Remove last cell</button>
<div>This first row has <output>2</output> cell(s).</div>
JavaScript
js
// Obtain relevant interface elements
const bodySection = document.querySelectorAll("tbody")[0];
const row = bodySection.rows[0]; // Select the first row of the body section
const cells = row.cells; // The collection is live, therefore always up-to-date
const cellNumberDisplay = document.querySelectorAll("output")[0];
const addButton = document.getElementById("add");
const removeButton = document.getElementById("remove");
function updateCellNumber() {
cellNumberDisplay.textContent = cells.length;
}
addButton.addEventListener("click", () => {
// Add a new cell at the end of the first row
const newCell = row.insertCell();
newCell.textContent = `Cell ${cells.length}`;
// Update the row counter
updateCellNumber();
});
removeButton.addEventListener("click", () => {
// Delete the row from the body
row.deleteCell(-1);
// Update the row counter
updateCellNumber();
});
结果
规范
| 规范 |
|---|
| HTML # dom-tr-insertcell-dev |
浏览器兼容性
加载中…
另见
HTMLTableElement.insertRow()- 代表单元格的 HTML 元素:
HTMLTableCellElement