如何确定选择器是在第一个还是最后一个位置

我使用goquery 的函数.Each()递归到子元素中。有没有办法找出这是否是父母的第一个(或最后一个)孩子?我尝试删除 HTML 节点的开始和尾随空格。检查第一个孩子可能是一个测试问题i == 0。但是最后一个子元素呢?

到目前为止,这是我的代码:

package main


import (

    "fmt"

    "io"

    "os"

    "strings"


    "github.com/PuerkitoBio/goquery"

)


// recursive function

func dumpElement(i int, sel *goquery.Selection) {

    fmt.Println("dump Element - is this the first or last element? I don't know")

    sel.Contents().Each(dumpElement)

}


func startRecursion(r io.Reader) error {

    g, err := goquery.NewDocumentFromReader(r)

    if err != nil {

        return err

    }


    g.Find(":root > body").Each(dumpElement)

    return nil

}


func main() {

    doc := `<!DOCTYPE html>

    <html><head><title>foo</title></head><body>

    <div class="bla">foo <b> bar </b> baz</div>

    </body></html>`


    if err := startRecursion(strings.NewReader(doc)); err != nil {

        os.Exit(-1)

    }

}


慕的地8271018
浏览 129回答 1
1回答

小怪兽爱吃肉

您很可能必须编写一个函数来返回您正在使用的函数,这样您就可以访问原始选择长度,例如:type iterator func(int, *goquery.Selection)func dumpElementFrom(s *goquery.Selection) iterator {&nbsp; &nbsp; lastIndex := s.Size() - 1&nbsp; &nbsp; return func(i int, sel *goquery.Selection) {&nbsp; &nbsp; &nbsp; &nbsp; if i == lastIndex {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Last Element")&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; sel.Contents().Each(dumpElement)&nbsp; &nbsp; }}func startRecursion(r io.Reader) error {&nbsp; &nbsp; g, err := goquery.NewDocumentFromReader(r)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; g.Find(":root > body").Each(dumpElementFrom(g))&nbsp; &nbsp; return nil}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go