我可以在cheerio中添加更多jquery选择器吗? (的node.js) [英] Can I add more jquery selectors to cheerio? (node.js)

查看:80
本文介绍了我可以在cheerio中添加更多jquery选择器吗? (的node.js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩cheerio,我注意到它似乎不支持jquery引用中指定的某些选择器,特别是:odd和:even。有没有办法通过将jquery包导入我的程序来使用它们?或者是必须在cheerio代码中实现的东西?

I've been playing around with cheerio and I noticed it doesn't seem to support certain selectors specified in the jquery reference, specifically ":odd" and ":even". Is there a way to use these by importing the jquery package into my program? Or is that something that has to be implemented into the cheerio code?

这是我的代码:

//var request = require('request');
var cheerio = require('cheerio');
var jquery = require('./jquery-1.10.2');

var fs = require('fs');

    $ = cheerio.load(fs.readFileSync('c:/java/bushkill_mls.html'));

    var odds = [];
    var evens = [];

    $('tr:odd').each(function() {
        odds = odds.concat($(this).text());

        });
        console.log(odds);

你可以看到我尝试导入jquery但我无法在不收到错误的情况下导入它窗口没有定义很明显这似乎是一个节点兼容性问题。那么有没有办法在cheerio中增加选择器库,或者可能导入另一个具有我需要的jquery选择器函数的模块?

You can see I tried importing jquery but I couldn't get past importing it without getting the error "window is not defined" so obviously this seems like a node compatibility problem. So is there any way to increase the selector library in cheerio or maybe import another module that has the jquery selector functions I need?

推荐答案

你可以像这样添加简单的cheerio:

You can add something simple to cheerio like this:

var cheerio = require('cheerio');

cheerio.prototype.odd = function() {
    var odds = [];
    this.each(function(index, item) {
        if (index % 2 == 1) {
            odds.push(item);
        }
    });

    return cheerio(odds);
}

var $ = cheerio.load("<div>0</div><div>1</div><div>2</div><div>3</div><div>4</div>");
$("div").odd().each(function() {
    console.log($(this).text());
});

是的,它与jquery完全不匹配,但它类似于cheerio如何处理jquery的:eq(n)选择器。

Yes, it doesn't match jquery exactly, but it's similar to how cheerio deals with jquery's :eq(n) selector.

这篇关于我可以在cheerio中添加更多jquery选择器吗? (的node.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆