Home > Web Front-end > JS Tutorial > How to use jQuery in Node.js

How to use jQuery in Node.js

怪我咯
Release: 2017-03-30 09:33:06
Original
1860 people have browsed it

First, we have to install jquery, npm install jquery. The installed version is 3.1.0

Then, the first impression is that we will use var $ = require('jquery').

Save the following code as app.js

var $ = require('jquery')
$("body").append("<p>TEST</p>");
console.log($("body").html());
Copy after login


Run node app.js. Prompt error:

Error: jQuery requires a window with a document

So what should we do?

On the homepage of npm's jquery installation package, we see that jsdom can be used to simulate a document.

require("jsdom").env("", function(err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
$("body").append("<p>TEST</p>");
console.log($("body").html());
});
Copy after login

Run, the result is OK.

One thing about the above code that makes me uncomfortable is that it needs to be operated in the callback function. So what can we do without introducing jquery in the callback function?

var $ = require(&#39;jquery&#39;)(require("jsdom").jsdom().defaultView);
$("body").append("<p>TEST</p>");
console.log($("body").html());
Copy after login

The same operation is OK.




The above is the detailed content of How to use jQuery in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template