Error: jQuery requires a window with a document

后端 未结 12 2347
说谎
说谎 2020-11-29 00:43

So everything was working just fine and great until doing npm update and now things do not work quite as they used to.

A little background: in my code I use jquery

12条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 01:10

    You can try the following with these version settings in your package.json:

    "jquery": "^2.1.1",
    "jsdom": "^1.0.0-pre.3"
    

    Say you have a file called page.htm:

    
    
    
        
        Document
    
    
        

    Html page

    left content

    Then, you can read from file, create a DOM and window from it with JSDOM and pass it to jquery:

    var jsdom = require("jsdom").jsdom;
    var fs = require('fs');
    fs.readFile('page.htm', {encoding: "utf8"}, function (err, markup) {
      if (err) throw err;
      var doc = jsdom(markup);
      var window = doc.parentWindow;
      var $ = require('jquery')(window)
      var outerLeft = $(".left").clone().wrap('
    ').parent().html(); var innerLeft = $(".left").html(); console.log(outerLeft, "and ...", innerLeft); });

    will output:

    left content

    and ...

    left content

提交回复
热议问题