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


当前回答

这些解决方案在我的电子应用程序中没有一个对我有帮助。

我的解决方案(变通方案):

npm install jquery

在index.js文件中:

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

在你的.js文件中,以这样的方式编写jQuery函数:

jQuery(document).ready(function() {

其他回答

警告

这个解决方案,正如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();
      });

更新(6月27日-18日):看起来jsdom有一个重大更新,导致原来的答案不再工作。我找到了这个解释如何使用jsdom的答案。我复制了下面的相关代码。

var jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = (new JSDOM('')).window;
global.document = document;

var $ = jQuery = require('jquery')(window);

注意:原来的答案没有提到你也需要使用npm install jsdom来安装jsdom

更新(2013年底):官方jQuery团队终于接管了npm上jQuery包的管理:

npm install jquery

然后:

require("jsdom").env("", function (err, window) {
    if (err) {
        console.error(err);
        return;
    }
    var $ = require("jquery")(window);
});

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

是的,jQuery可以与Node.js一起使用。

步骤包括jQuery在节点项目:-

NPM jquery——保存 在代码中包含jquery

import jQuery from 'jquery';

const $ = jQuery;

我确实在node.js项目中一直使用jquery,特别是在chrome扩展的项目中。

例如,https://github.com/fxnoob/gesture-control-chrome-extension/blob/master/src/default_plugins/tab.js

从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);

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