Select 兄弟姐妹 & parent 与 Cheerio

Select sibling & parent with Cheerio

我一直无法使用 cheerio 访问非常简单的 HTML 片段,我刚刚打开 object $(this) object 并进行了追踪正是我需要的。现在当堆栈中没有 object 时会发生错误,例如兄弟或 child。 select 前一个兄弟的正确方法是什么,获取它的名称、href 和内容,以及 parent 的 css.

var code = $('code.lang-javascript, code.lang-js')
dataSet.blocks = []
code.map(function (i, elm) {
  var block = {}
  block.prevSiblingTag = $(this).parent().prev()[0].children[0].name
  block.prevSiblingHref = $(this).parent().prev()[0].children[0].attribs.href
  block.prevSiblingContent = $(this).parent().prev()[0].children[0].text()
  block.parentTag = $(this)[0].name
  block.parentClass = $(this)[0].attribs.class
  block.code = $(this).html()
  dataSet.blocks.push(block)
})

我在做这个,结果一团糟。

var $parent = $($(this).parent().html())
var $prevSibling = $($(this).parents().prev())
var block = {}
block.parentClass = $parent.attr('class')
block.prevSibling = $prevSibling.html()
block.code = $(this).html()

问题是,如果前一个兄弟没有 children,那么 $(this).parent().prev()[0] 将为空。

因此,最好获取对目标元素的 jQuery 对象引用,然后使用它来获取 attribute/property 值,例如

var code = $('code.lang-javascript, code.lang-js')
dataSet.blocks = code.map(function (i, elm) {
    var block = {}, $this = $(this),
        target = $this.parent().prev().children().eq(0);
    block.prevSiblingTag = target.attr('name');
    block.prevSiblingHref = target.attr('href');
    block.prevSiblingContent = target.text()
    block.parentTag = this.name
    block.parentClass = $this.attr('class')
    block.code = $this.html()
    return block;
}).get();

此外,由于您使用的是 .map(),它可以 return 一个数组