【问题标题】:In Tritium, how can I select the previous/next element?在 Tritium 中,如何选择上一个/下一个元素?
【发布时间】:2013-06-25 01:37:08
【问题描述】:

我正在使用 Moovweb SDK 来转换网站,并且我有很多页面的内容都与这种格式匹配。有一个 <h2> 开始一个部分,并且该部分具有随机数量的 <p> 元素。

由于这些元素没有属性,我无法按类或 id 进行选择。我想在每个部分中选择第一个和最后一个 <p>。我不想手动选择$('./p[1]')$('./p[4]') 等...有没有办法在每个<h2> 之前和之后选择元素?

<div>
  <h2>This is a heading</h2>
  <p>Here is some content</p>
  <p>Meh</p>
  <p>Here's another paragraph</p>
  <p>Important sentence because it's the last one</p>
  <h2>Here's a subheading</h2>
  <p>Topic sentence</p>
  <p>Bleh bleh bleh</p>
  <p>Hurray, this fragment.</p>
  <p>May the Force be with you</p>
  <p>Moovweb rocks!</p>
  <h2>New heading</h2>
  <p>More awesome content here</p>
  <p>Why is there so much stuff?</p>
  <h2>The end</h2>
  <p>Or is it?</p>
</div>

【问题讨论】:

    标签: xpath moovweb tritium


    【解决方案1】:

    您可以在 XPath 中使用 preceding-siblingfollowing-sibling 选择器来执行此操作!

    代码如下所示:

    $("./div"){
      $("./h2") {
        $("following-sibling::p[1]") { # first p after h2
          # do stuff
        }
        $("preceding-sibling::p[1]") { # first p before h2
          # do stuff
        }
      }
    }
    

    查看我在 Tritium Tester 中创建的示例:http://tester.tritium.io/dc25a419ac15fad70fba6fd3d3a9b512cb8430e8

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2012-06-13
      • 2016-04-18
      • 2010-12-16
      • 1970-01-01
      相关资源
      最近更新 更多