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

HTMLTableRowElement:deleteCell() 方法

· 52CE 我爱测

HTMLTableRowElement 接口的 **`deleteCell()`** 方法从给定的 tr 中移除特定的行单元格。

HTML DOM

HTMLTableRowElement 接口的 deleteCell() 方法从给定的 tr 中移除特定的行单元格。

语法

deleteCell(index)

参数

  • index
    • : 要移除单元格的单元格索引。如果 index 值是 -1 或者等于单元格的数量,则移除行的最后一个单元格。

返回值

无(undefined)。

异常

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

示例

此示例使用 HTMLTableRowElement.insertCell() 将新的单元格附加到行中。

HTML

<table>
  <thead>
    <tr>
      <th>C1</th>
      <th>C2</th>
      <th>C3</th>
      <th>C4</th>
      <th>C5</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>单元格 1</td>
      <td>单元格 2</td>
    </tr>
  </tbody>
</table>

<button id="add">添加单元格</button>
<button id="remove">移除最后的单元格</button>
<div>第一行有 <output>2</output> 个单元格。</div>
table {
  border-collapse: collapse;
}

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

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

JavaScript

// 获取相关接口元素
const bodySection = document.querySelectorAll("tbody")[0];
const row = bodySection.rows[0]; // 选择表格体部分的第一行
const cells = row.cells; // 集合是动态的,因此总是最新的
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", () => {
  // 在第一行的末尾添加单元格
  const newCell = row.insertCell();
  newCell.textContent = `单元格 ${cells.length}`;

  // 更新行数
  updateCellNumber();
});

removeButton.addEventListener("click", () => {
  // 从表格体删除行
  row.deleteCell(-1);

  // 更新行数
  updateCellNumber();
});

结果

示例

规范

浏览器兼容性

参见

  • HTMLTableElement.insertRow()
  • 表示单元格的 HTML 元素:HTMLTableCellElement

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

资料来源与适用范围

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

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

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