首页 > 解决方案 > 如何通过 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()函数,但我无法让它正常运行,即返回一个数字。

标签: javascriptjqueryxpathcss-selectors

解决方案


在 HTML 表格 DOM 中,一个单元格具有一个属性cellIndex(以 0 开头),因此您可以使用例如 找到 XPath 的索引x.cellIndex + 1。然后您可以"id('insertGuidHere')/td[" + (x.cellIndex + 1) + "]"在 XPath 中使用来选择第三个单元格。这当然也适用于例如//tbody/tr/td[3]选择所有行的所有第三个单元格。


推荐阅读