如何在Node.js中使用jQuery
jQuery是一个JavaScript库,它为我们提供了与vanilla JavaScript相同的功能,但代码行数较少。对jQuery的需求减少了,因为随着更新,在vanilla JavaScript中做事变得简单多了。虽然它的受欢迎程度在下降,但仍有大约76%的项目使用jQuery。
我们的目标是在Node.js中使用jQuery:我们可以使用jquery模块在Node.js中使用jQuery。
注意:使用 “jquery “模块,而不是 “jQuery “模块,因为后者已被废弃。
让jQuery在Node.js中工作:
npm init -y
‘-y’标签使得在创建package.json文件时问的所有问题的默认答案都是yes。
npm install jquery
npm install jsdom
const jsdom = require('jsdom')
const dom = new jsdom.JSDOM("")
const jquery = require('jquery')(dom.window)
就这样,我们已经成功地将jquery加载到我们的Node.js应用程序中。
例子:为了更好地了解它是如何工作的,请通过下面的例子:-
// Importing the jsdom module
const jsdom = require("jsdom");
// Creating a window with a document
const dom = new jsdom.JSDOM(`<!DOCTYPE html>
GeeksforGeeks
`);
// Importing the jquery and providing it
// with the window
const jquery = require("jquery")(dom.window);
// Appending a paragraph tag to the body
jquery("body").append("Is a cool Website
");
// Getting the content of the body
const content = dom.window.document.querySelector("body");
// Printing the content of the heading and paragraph
console.log(content.textContent);
输出:
GeeksforGeeks
Is a cool website