【问题标题】:How to map html table header cell to a row cell via css or xpath selectors?如何通过 css 或 xpath 选择器将 html 表头单元格映射到行单元格?
【发布时间】:2018-10-31 11:58:16
【问题描述】:

所以我在页面中有这样的数据结构:

<!-- 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() 函数,但我无法让它正常运行,即返回一个数字。

【问题讨论】:

    标签: javascript jquery xpath css-selectors


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-03-11
      • 2018-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多