javascript - 如何通过 css 或 xpath 选择器将 html 表头单元格映射到行单元格?
问题描述
所以我在页面中有这样的数据结构:
<!-- some html-->
<table>
<thead>
<tr>
<th>Date</th><th>Type</th><th>Value</th> <!-- Header I need -->
</tr>
</thead>
</table>
<!-- some html-->
<table>
<tbody>
<tr id="insertGuidHere">
<td>eventDate</td><td>eventType</td><td>eventData</td> <!-- Values I need to map -->
</tr>
</tbody>
</table>
我有一个标题行,在不同级别的不同表格中的某处我有数据行(一个过于复杂的剑道网格)。我不能通过合理的 xpath 从一个到另一个,但我知道索引匹配正确。
我想要的是一种将标头索引映射到数据的方法。类似反向的东西nth-child()
- 我通过文本找到元素并返回它的索引
var x = $x("//th[contains(text(),'Value')]")[0].findIndexAmongSiblings(); // returns 3, because it's 3rd header cell
$("tr#insertGuidHere > td:nth-child(" + x + ")"); // returns eventData cell
我知道 jQuery 中有一个.index()
函数,但我无法让它正常运行,即返回一个数字。
解决方案
在 HTML 表格 DOM 中,一个单元格具有一个属性cellIndex
(以 0 开头),因此您可以使用例如 找到 XPath 的索引x.cellIndex + 1
。然后您可以"id('insertGuidHere')/td[" + (x.cellIndex + 1) + "]"
在 XPath 中使用来选择第三个单元格。这当然也适用于例如//tbody/tr/td[3]
选择所有行的所有第三个单元格。
推荐阅读
- mysql - MYSQL全文匹配未返回预期结果
- php - How can I hide a button with php if it does not correspond to an id of a session?
- php - 在 Woocommerce 中启用计算的购物车折扣限制
- git - 如何在 repo 上获取文件忽略本地更改
- c++ - 如何让 gtest 框架完全覆盖而不是部分覆盖“新”和“删除”。与 2015 年相比
- reflection - 如何通过反射收集成员以稍后作为参数传递
- mysql - Maria MySQL 从 10.1.x 升级到 10.2.x 但现在信号量等待时间很长
- c++ - 从整数指针向量打印值
- typescript - 如何在 Firebase 函数(打字稿)中将 Class 分配给从 Firestore 检索到的数据?
- python-3.x - PyCharm中如何导入模块