将 require('jquery') 与 jsdom 一起使用?
我可以使用 JSDOM 的“脚本”选项来加载 jquery 进行抓取。然而我想知道现在 npm 包含 jquery 是否有可能使用节点自己的 require 机制,并且更好或更坏。
jsdom = require 'jsdom'
config =
html: "<html><body></body></html>"
scripts: ['http://code.jquery.com/jquery-1.5.min.js']
jsdom.env config, (err, window) ->
$ = window.jQuery;
$('body').append("<div class='testing'>Hello World</div>")
console.log(window.document.innerHTML)
一切正常并显示更新的文档。但现在我们也可以运行:
$ = require 'jquery'
$('body').append("<div class='testing'>Hello World</div>")
我发现它更简洁 - 我只是不太确定如何以这种较新的方式使用 jquery 和 jsdom。具体来说,window对象在哪里?
I can use JSDOM's 'scripts' option to load jquery for scraping. However I was wondering if it was possible, and also better or worse, to use node's own require mechanism now npm includes jquery.
jsdom = require 'jsdom'
config =
html: "<html><body></body></html>"
scripts: ['http://code.jquery.com/jquery-1.5.min.js']
jsdom.env config, (err, window) ->
$ = window.jQuery;
$('body').append("<div class='testing'>Hello World</div>")
console.log(window.document.innerHTML)
All works fine and shows the updated document. But these days we can also run:
$ = require 'jquery'
$('body').append("<div class='testing'>Hello World</div>")
Which I find neater - I'm just not quite sure of how to use jquery and jsdom in this newer manner. Specifically, where is the window object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
下面的最终工作代码 - 看起来 node-jquery 在“body”处有一个预先构建的空文档,要访问最终文档,您只需在其上运行 .html() 即可。
Final working code below - it looks like node-jquery has an pre-built, empty document at 'body', to access the final document, you can just run .html() on it.
如果您确实需要访问窗口:
请谨慎使用,
._
属性被视为私有If you really need to get at the window:
Use with caution,
._
properties are seen as private我不认为你能做到这一点。您正在从 JSDOM
window
对象中获取 jQuery 对象的特定实例,而require 'jquery'
将获取 jQuery 模块。相反,您需要特定于该 JSDOM 窗口的jQuery
对象版本,这意味着执行$ = window.jQuery
I don't think you can do this. You are grabbing a specific instance of the jQuery object off of the JSDOM
window
object, whereasrequire 'jquery'
would grab the jQuery module. You need a version of thejQuery
object specific to that JSDOM window, instead, which means doing$ = window.jQuery