【问题标题】:In Tritium, how can I insert elements based on content of existing elements?在 Tritium 中,如何根据现有元素的内容插入元素?
【发布时间】:2013-06-21 01:07:37
【问题描述】:

我想插入新元素,但它必须在特定元素之间。区分这些元素的唯一方法是通过它们的内容。

我想插入将按字母顺序拆分此列表的标题元素。我该怎么做?

<p>Aardvark</p>
<p>Alligator</p>
<p>Bear</p>
<p>Beaver</p>
<p>Cat</p>
<p>Cow</p>
...

【问题讨论】:

    标签: html sdk moovweb


    【解决方案1】:

    好的,我们现在就开始编写一些严肃的代码。

    我将尝试使这种动态化!

    $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)
          }
        }
      }
    }
    

    【讨论】:

    • 我在这里唯一要改变的是使用“捕获”而不是“替换”,因为你实际上并没有替换任何东西。
    【解决方案2】:

    试一试。它适用于任何列表,即使元素未按首字母分组。

    $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 来匹配找到的字母的小写和大写版本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多