编程语言
首页 > 编程语言> > node与jquery交互

node与jquery交互

作者:互联网

今天用node引入jquery的包来进行遍历数组的时候发现出了一个错误
image.png

$.each(arr1, function (i, val) {
  ^

TypeError: $.each is not a function
    at Object.<anonymous> (d:\Documents\Codes\WebstormProjects\webtutor\jqtest\cee.js:3:3)
    at Module._compile (internal/modules/cjs/loader.js:799:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:810:10)
    at Module.load (internal/modules/cjs/loader.js:666:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:606:12)
    at Function.Module._load (internal/modules/cjs/loader.js:598:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:862:12)
    at internal/main/run_main_module.js:21:11

[Done] exited with code=1 in 0.643 seconds

而引入其他的包就没有问题,网上查了一下才知道要这么做:

var jsdom = require("jsdom"); 
$ = require("jquery")(jsdom.jsdom().createWindow()); 
console.lo($);

或者

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM(`<!DOCTYPE html>`);
const $ = require('jQuery')(window);
console.log($); //测试jquery是否可以正常工作

要定义一个jsdom来模拟他的环境这样就好了;

推荐一个工具包 licia很好用的

var bubblesort = require('licia/bubbleSort')
var camelCase = require('licia/camelCase')
console.log(bubblesort([5, 3, 3, 2, 7, 8, 84, 5, 89, 9, 8]));
console.log(camelCase('foo-bar')); // -> fooBar
console.log(camelCase('foo bar')); // -> fooBar
console.log(camelCase('foo_bar')); // -> fooBar
console.log(camelCase('foo.bar')); // -> fooBar

结果:

[ 2, 3, 3, 5, 5, 7, 8, 8, 9, 84, 89 ]
fooBar
fooBar
fooBar
fooBar

[Done] exited with code=0 in 0.556 seconds

里面封装了很多函数,我们直接调用就可以

标签:node,jquery,console,fooBar,js,internal,jsdom,loader,交互
来源: https://www.cnblogs.com/yzqdev/p/10568207.html