jQuery不工作,但document.querySelector做(CasperJS)

时间:2014-02-22 06:35:07

标签: javascript jquery casperjs

网站在h1标记中显示访问者的IP地址id = "ip"

当我使用return document.querySelector('#ip').innerText;时,它会显示正确的IP地址,一切都很顺利。

但是,当我使用return $('#ip').text();时,会显示null

任何想法为什么?

var casper = require('casper').create();

casper.start("http://mikeyaworski.com/IP", function() {

    var ip = this.evaluate(function() {
        // return document.querySelector('#ip').innerText; // does work
        return $('#ip').text(); // doesn't work, but it should
    });

    this.echo("\nYour public IP address is: " + ip);
});

casper.run();

2 个答案:

答案 0 :(得分:1)

我最终将jQuery从here下载到我计算机上的某个位置。

然后我关注了这个主题的documentation,它似乎有用(奇怪的是,因为在过去,我不需要遵循这些“规则”)。

我的代码最终是这样的:

var casper = require('casper').create();

casper.start("http://mikeyaworski.com/IP", function() {

    // this is the changed part
    casper.page.injectJs('path/to/jquery-1.11.0.js');

    var ip = this.evaluate(function() {
        // return document.querySelector('#ip').innerText;
        return $('#ip').text();
    });

    this.echo("\nYour public IP address is: " + ip);
});

casper.run();

这也很有效:

// this is the changed part
var casper = require('casper').create({
    clientScripts: ["path/to/jquery-1.11.0.js"]
});

casper.start("http://mikeyaworski.com/IP", function() {

    var ip = this.evaluate(function() {
        // return document.querySelector('#ip').innerText;
        return $('#ip').text();
    });

    this.echo("\nYour public IP address is: " + ip);
});

casper.run();

然而,我仍然觉得奇怪的是,在this other script上,我使用jQuery就好了,无需将其注入任何地方,甚至将其下载到我的计算机上。我想了解更多相关信息。

答案 1 :(得分:0)

显然,页面上jQuery的早期版本可能会与您在测试中使用的jQuery版本发生冲突。如果您升级版本,两个jQuerys不会发生冲突。这与其他线程有关:

CasperJS click event having AJAX call

还有其他方法可以在不更改jQuery版本的情况下修复它。

相关问题