HTMLTableSectionElement:deleteRow() 方法
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
无( 如果 HTMLTableSectionElement
接口的 deleteRow()
方法从给定的 中移除特定的行(
)。 语法
deleteRow(index)
参数
index
index
是一个表示应该删除行的整数。然而,特殊索引 -1
可以用于删除当前分段的最后一行。返回值
undefined
)。异常
IndexSizeError
DOMException
index
大于等于行数或小于 -1
,则抛出该异常。示例
HTML
列 1
列 2
列 3
X
Y
Z
JavaScript
// 获取相关接口元素
const bodySection = document.querySelectorAll("tbody")[0];
const rows = bodySection.rows; // 集合是动态的,因此其总是最新的
const rowNumberDisplay = document.querySelectorAll("output")[0];
const addButton = document.getElementById("add");
const removeButton = document.getElementById("remove");
function updateRowNumber() {
rowNumberDisplay.textContent = rows.length;
}
addButton.addEventListener("click", () => {
// 在主体的末尾添加一个新行
const newRow = bodySection.insertRow();
// 在新行内添加单元格
["A", "B", "C"].forEach(
(elt) => (newRow.insertCell().textContent = `${elt}${rows.length}`),
);
// 更新行计数
updateRowNumber();
});
removeButton.addEventListener("click", () => {
// 从主体删除行
bodySection.deleteRow(-1);
// 更新行计数
updateRowNumber();
});
结果
规范
Specification HTML
# dom-tbody-deleterow浏览器兼容性
参见