dream752614590 2019-03-04 15:40
浏览 41
已采纳

如何找出选择器在第一个还是最后一个位置

I use goquery's function .Each() to recurse into the child elements. Is there a way to find out if this is the first (or last) child of a parent? I try to remove starting and trailing whitespace of HTML nodes. Checking for the first child is probably a matter of testing i == 0. But what about the last child element?

This is my code so far:

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)
    }
}
  • 写回答

1条回答 默认 最新

  • dsiftnc99059 2019-03-04 18:45
    关注

    Most likely you'd have to write a function that returns the funciton you are using, so you get access to the original selections length, something like:

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件