此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

HTMLTableCellElement:cellIndex 属性

基线 广泛可用

自 2015年7月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

HTMLTableCellElement 接口的 cellIndex 只读属性表示单元格在其所在行(<tr>)中的位置。第一个单元格的索引是 0。

值

返回单元格的索引,或如果单元格不属于任何行,则返回 -1。

示例

此示例为 tbody 中第一行的所有单元格编号添加标签。

HTML

html
<table>
  <thead>
    <tr>
      <th>商品</th>
      <th>ä»·æ ¼</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>香蕉</td>
      <td>$2</td>
    </tr>
    <tr>
      <td>大米</td>
      <td>$2.5</td>
    </tr>
  </tbody>
</table>

JavaScript

js
const rows = document.querySelectorAll("tbody tr");
const cells = rows[0].cells;

for (const cell of cells) {
  cell.textContent = `${cell.textContent}(单元格 #${cell.cellIndex})`;
}

结果

规范

规范
HTML
# dom-tdth-cellindex

浏览器兼容性