簡體   English   中英

在Tritium中,如何選擇上一個/下一個元素?

[英]In Tritium, how can I select the previous/next element?

我正在使用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中使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM