[英]In Tritium, how can I insert elements based on content of existing elements?
我想插入新元素,但它必須在特定元素之間。 區分這些元素的唯一方法是它們的內容。
我想插入將按字母順序拆分此列表的標題元素。 我怎樣才能做到這一點?
<p>Aardvark</p>
<p>Alligator</p>
<p>Bear</p>
<p>Beaver</p>
<p>Cat</p>
<p>Cow</p>
...
好吧,讓我們現在正確地完成一些嚴肅的代碼。
我打算讓這個充滿活力!
$letter = ''
$("//p[not(contains(@class,'starts-with'))][1]") {
# get the first p that doesn't have the class
$add_header = "false"
text() {
capture(/\A(\w)/) {
# get the first letter and set it to a variable
match($letter) {
with($1) {
#do nothing
}
else() {
$letter = $1
$add_header = "true"
}
}
}
}
match($add_header) {
with(/true/) {
insert_before("h1", "Starts With: "+$letter)
$("self::*|following-sibling::p[contains(text(), '"+$letter+"')]") {
add_class("starts-with-" + $letter)
}
}
}
}
試一試。 即使元素沒有按首字母分組,它也適用於任何列表。
$add_header = "true"
text() {
replace(/^(.)/) {
$first_letter = $1
}
}
# If the header section already exists, move this element inside
move_to("preceding-sibling::div[@class='starts-with-"+$first_letter+"']") {
$add_header = "false"
}
# If the header section doesn't exist, wrap the element
match($add_header, /true/) {
wrap("div") {
add_class("starts-with-" + $1)
}
}
將它包裝成一個函數是非常簡單的。 在此之后,要編寫的下一個邏輯函數將是字母順序,以及使用$ first_letter匹配找到的字母的小寫和大寫版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.