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

cdb*_*a89 5 javascript function node.js cheerio

我有几个实用函数,可以对 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");
    });
}
Run Code Online (Sandbox Code Playgroud)

对于这个问题是否有一个优雅的解决方案,允许我只将 1 个参数传递给我的函数?(我并不是说将它们包装到对象文字中:>)。因为坦率地说,这种方式不太好(除非我忽略了某些事情)。

Jac*_*ack 4

似乎你可以做这样的事情:

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"));
})();
Run Code Online (Sandbox Code Playgroud)