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"); 
    }); 
} 

有一种优雅的解决这个问题,让我通过只有1参数去我的功能呢? (我不是说将它们包装到一个对象文字中:>)。因为坦率地说,这种方式并不好(除非我忽略了某些东西)。

+3

为什么你需要通过''$呢?你不能只在你的模块的顶部有'var $ = require('cheerio');'? – Jack 2015-02-06 02:54:43

好像你可以只是做这样的事情:

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")); 
})();