大网数据广告活动
Web 标准与前端开发

HTMLTableSectionElement:deleteRow() 方法

· 52CE 我爱测

HTMLTableSectionElement 接口的 **`deleteRow()`** 方法从给定的 section 中移除特定的行(tr)。

HTML DOM

HTMLTableSectionElement 接口的 deleteRow() 方法从给定的 section 中移除特定的行(tr)。

语法

deleteRow(index)

参数

  • index
    • : index 是一个表示应该删除行的整数。然而,特殊索引 -1 可以用于删除当前分段的最后一行。

返回值

无(undefined)。

异常

  • IndexSizeError DOMException
    • : 如果 index 大于等于行数或小于 -1,则抛出该异常。

示例

在这个示例中,有两个按钮允许你对表格主体添加和移除行,它还使用表中当前行数更新 output 元素。

HTML

<table>
  <thead>
    <th>列 1</th>
    <th>列 2</th>
    <th>列 3</th>
  </thead>
  <tbody>
    <tr>
      <td>X</td>
      <td>Y</td>
      <td>Z</td>
    </tr>
  </tbody>
</table>
<button id="add">添加一行</button>
<button id="remove">移除最后一行</button>
<div>表格主体有 <output>1</output> 行。</div>
table {
  border-collapse: collapse;
}

th,
td {
  border: 1px solid black;
}

button {
  margin: 1em 1em 1em 0;
}

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();
});

结果

示例

规范

浏览器兼容性

参见

  • HTMLTableElement.deleteRow()

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。