jquery 通过表头获取列
时间: 2023-08-03 18:06:37 浏览: 50
如果您想要通过表头获取某一列的数据,您可以先获取表头元素,然后使用 `index()` 函数获取该表头元素在表格中的索引,最后使用 `eq()` 函数选择该索引所对应的列元素。
例如,假设您有以下 HTML 表格:
```html
<table id="myTable">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>25</td>
<td>Male</td>
</tr>
<tr>
<td>Jane</td>
<td>30</td>
<td>Female</td>
</tr>
<tr>
<td>Bob</td>
<td>40</td>
<td>Male</td>
</tr>
</tbody>
</table>
```
您可以使用以下代码来获取表头中的某一列数据:
```javascript
// 获取表头元素
var $headers = $('#myTable th');
// 获取 "Age" 表头元素的索引
var ageIndex = $headers.index($('#myTable th:contains("Age")'));
// 获取所有行中 "Age" 列的元素
var $ageCells = $('#myTable tr td:nth-child(' + (ageIndex + 1) + ')');
// 输出所有 "Age" 列的数据
$ageCells.each(function() {
console.log($(this).text());
});
```
在此示例中,我们首先使用 `$headers` 变量获取所有表头元素,然后使用 `index()` 函数查找包含文本 "Age" 的表头元素的索引。注意,`index()` 函数返回的索引值是从 0 开始计数的,因此我们需要在选择列元素时将索引值加 1。最后,我们使用 `each()` 函数遍历所有 "Age" 列的元素,将其文本内容输出到控制台。