1
我想插入新元素,但它必须在特定元素之间。区分这些元素的唯一方法是通过其内容。在Tritium中,我如何根据现有元素的内容插入元素?
我想插入将按字母顺序拆分这个列表的标题元素。我怎样才能做到这一点?
<p>Aardvark</p>
<p>Alligator</p>
<p>Bear</p>
<p>Beaver</p>
<p>Cat</p>
<p>Cow</p>
...
我想插入新元素,但它必须在特定元素之间。区分这些元素的唯一方法是通过其内容。在Tritium中,我如何根据现有元素的内容插入元素?
我想插入将按字母顺序拆分这个列表的标题元素。我怎样才能做到这一点?
<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匹配找到的字母的大写和小写版本。
我唯一要改变的地方就是使用“capture”而不是“replace”,因为你实际上并没有取代任何东西。 – noj
@noj谢谢!我总是忘记功能存在! –
已添加。^_ ^干杯! –