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

How to find out if selector is at first or last position

我使用 goquery's function .Each() 递归到 child 元素。有没有办法查明这是否是第一个(或最后一个)parent 的 child?我尝试删除 HTML 节点的开始和尾随空格。检查第一个 child 可能是测试 i == 0 的问题。但是最后一个 child 元素呢?

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

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

很可能您必须编写一个 returns 您正在使用的函数的函数,这样您就可以访问原始选择长度,例如:

type iterator func(int, *goquery.Selection)

func dumpElementFrom(s *goquery.Selection) iterator {
    lastIndex := s.Size() - 1
    return func(i int, sel *goquery.Selection) {
        if i == lastIndex {
            fmt.Println("Last Element")
        }
        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(dumpElementFrom(g))
    return nil
}