Cheerio:需要将 $ 与元素一起传递吗?

Cheerio: need to pass around $ along with elements?

我有几个实用函数,它们对 cheerio 对象进行操作。对于这些函数中的几乎每一个,我都必须将 $ 与元素本身一起传递。

示例:

function aUtilityFunc($, cheerioEl) { // <- $ in the params
    return cheerioEl.each(function (i, child) {
        // i do not want to do this:
        $(child).attr("something", $(child).attr("something") + "something");

        // i would rather do this and omit the $ in the params (like with global jquery doc):
        var $ = cheerioEl.$;
        $(child).attr("something", $(child).attr("something") + "something");
    });
}

对于这个问题是否有一个优雅的解决方案,允许我只向我的函数传递 1 个参数? (我不是说将它们包装成对象字面量 :>)。因为坦率地说,这样不是很好(除非我忽略了什么)。

看来你可以这样做:

var $ = require('cheerio');

function aUtilityMethod(cEls) {
    cEls.each(function(i, a) {
        console.log("li contains:", $(a).html());
    });
}


// testing utility method
(function() {
    var fakeDocument = "<html><body><ol><li>one</li><li>two</li></ol></body></html>",
        myDoc = $(fakeDocument),
        myOl = $("ol", myDoc.html());

    aUtilityMethod(myOl.find("li"));
})();