aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/htmltablerowelement/rowindex/index.md
blob: 985e2e7074f494bfc7ad207eeed5e8337c0d6b19 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
---
title: HTMLTableRowElement.rowIndex
slug: Web/API/HTMLTableRowElement/rowIndex
tags:
  - API
  - HTML DOM
  - NeedsSpecTable
  - Property
  - Reference
translation_of: Web/API/HTMLTableRowElement/rowIndex
---
{{APIRef("HTML DOM")}}

只读属性 **`HTMLTableRowElement.rowIndex`** 用于表示元素所在行相对于整个 {{HtmlElement("table")}} 的逻辑位置。

即使 {{HtmlElement("thead")}}、{{HtmlElement("tbody")}} 和 {{HtmlElement("tfoot")}}} 元素在 HTML 中乱序排列,浏览器也会以正确的顺序渲染表格。因此,行号的标记顺序为:从 `<thead>``<tbody>`,再到 `<tfoot>`## 语法

```js
var index = HTMLTableRowElement.rowIndex
```

### 返回值

返回该行的索引,如果该行不属于表的一部分,则返回 `-1`## 示例

本示例使用 JavaScript 标记表中的所有行号。

### HTML

```html
<table>
  <thead>
    <tr><th>商品</th>       <th>价格</th></tr>
  </thead>
  <tbody>
    <tr><td>香蕉</td>       <td>$2</td></tr>
    <tr><td>橘子</td>       <td>$8</td></tr>
    <tr><td>西冷牛排</td>   <td>$20</td></tr>
  </tbody>
  <tfoot>
    <tr><td>总计</td>       <td>$30</td></tr>
  </tfoot>
</table>
```

### JavaScript

```js
let rows = document.querySelectorAll('tr');

rows.forEach((row) => {
  let z = document.createElement("td");
  z.textContent = `(row #${row.rowIndex})`;
  row.appendChild(z);
});
```

### 结果

{{EmbedLiveSample("Example")}}

## 浏览器兼容性

{{Compat}}