是否有可能在服务器端使用Node.js使用jQuery选择器/DOM操作?


当前回答

警告

这个解决方案,正如Golo Roden提到的是不正确的。它只是一个快速修复,帮助人们使用Node应用程序结构运行实际的jQuery代码,但它不是Node哲学,因为jQuery仍然运行在客户端,而不是在服务器端。我很抱歉给了一个错误的答案。


您还可以使用节点渲染Jade,并将jQuery代码放在其中。下面是jade文件的代码:

!!! 5
html(lang="en")
  head
    title Holamundo!
    script(type='text/javascript', src='http://code.jquery.com/jquery-1.9.1.js')
  body
    h1#headTitle Hello, World
    p#content This is an example of Jade.
    script
      $('#headTitle').click(function() {
        $(this).hide();
      });
      $('#content').click(function() {
        $(this).hide();
      });

其他回答

据我所知没有。DOM是一个客户端的东西(jQuery不解析HTML,但解析DOM)。

下面是一些当前的Node.js项目:

https://github.com/ry/node/wiki (https://github.com/nodejs/node)

SimonW的djangode非常酷…

另一种选择是使用Underscore.js。它应该提供您可能需要的JQuery服务器端功能。

2016年,事情就简单多了。使用控制台将jquery安装到node.js:

npm install jquery

将它绑定到node.js代码中的变量$(例如-我习惯了它):

var $ = require("jquery");

做的东西:

$.ajax({
    url: 'gimme_json.php',
    dataType: 'json',
    method: 'GET',
    data: { "now" : true }
});

也适用于gulp,因为它基于node.js。

jQuery模块可以通过以下方式安装:

npm install jquery

例子:

var $ = require('jquery');
var http = require('http');

var options = {
    host: 'jquery.com',
    port: 80,
    path: '/'
};

var html = '';
http.get(options, function(res) {
res.on('data', function(data) {
    // collect the data chunks to the variable named "html"
    html += data;
}).on('end', function() {
    // the whole of webpage data has been collected. parsing time!
    var title = $(html).find('title').text();
    console.log(title);
 });
});

jQuery在Node.js中的引用**:

http://quaintous.com/2015/07/31/jqery-node-mystery/ http://www.hacksparrow.com/jquery-with-node-js.html

从jsdom v10开始,.env()函数已弃用。在尝试了很多需要jquery的东西之后,我这样做了:

Var jsdom = require('jsdom'); const {JSDOM} = JSDOM; const {window} = new JSDOM(); const {document} = (new JSDOM(")).window; 全球。文档=文档; var $ = jQuery = require(' jQuery ')(window);

希望这对你或任何面临这类问题的人有所帮助。