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


当前回答

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

其他回答

警告

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

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是一个很棒的工具。但如果你想评估整个页面,并在服务器端做一些奇怪的事情,我建议在它们自己的上下文中运行它们:

vm.runInContext

所以像require / CommonJS这样的东西不会破坏你的Node进程本身。

你可以在这里找到相关文档。干杯!

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

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

npm install jquery

在index.js文件中:

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

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

jQuery(document).ready(function() {

首先,安装它

npm install jquery -S

安装后,您可以如下所示使用它

import $ from 'jquery';
window.jQuery = window.$ = $;
$(selector).hide();

你可以查看我写的完整教程:https://medium.com/fbdevclagos/how-to-use-jquery-on-node-df731bd6abc7