无法从*goquery.Selection选择直接子元素

huangapple go评论72阅读模式
英文:

Cannot Select Direct Child from *goquery.Selection

问题

在jQuery和CSS中,你可以使用>字符来指向只有直接子元素。

Goquery中,可以使用类似doc.Find("body > ul")的方式实现这一点,但是当你已经有一个*goquery.Selection并且想要选择选择集的直接子元素时,该如何操作呢?

例如:

doc.Find("body > ul > li") // 正常工作

doc.Find("body > ul > li").Each(func(i int, s *goquery.Selection) {
    s.Find("> ul") // 不起作用
})

我想要实现的是从第二个代码块中所选取的结果,但是我尝试了很多方法都没有成功。

该如何实现呢?

英文:

In jQuery and CSS, you can use the > character which points to only the direct child element.

This works in Goquery with something like doc.Find("body > ul"), but when you already have a *goquery.Selection and you want to select a direct child element of the selection, how can this be done?

For example:

doc.Find("body > ul > li") // Works

doc.Find("body > ul > li").Each(func(i int, s *goquery.Selection) {
    s.Find("> ul") // Does not work
})

I want to accomplish what you'd expect to be selected from the second block of code but I haven't had any success with this.

How can this be done?

答案1

得分: 4

这个 cascadia ticket(goquery使用的选择器库)中所述,这个功能目前没有被实现,也不会被实现。

最简单的解决方法是在你的选择器上使用ChildrenFiltered()方法:

doc.Find("body > ul > li").Each(func(i int, s *goquery.Selection) {
    s.ChildrenFiltered("ul")
})
英文:

As noted in this cascadia ticket (the selector library that goquery uses), this functionality is not (and will not be) implemented.

The simplest workaround would be to use the ChildrenFiltered() method on your selection:

doc.Find("body > ul > li").Each(func(i int, s *goquery.Selection) {
    s.ChildrenFiltered("ul")
})

huangapple
  • 本文由 发表于 2017年8月28日 17:36:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/45915940.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定