2013-03-24 166 views
3

我看起来像当我通过jsdom运行页面时,页脚本中的$(document).ready块没有被执行。

下面是HTML:

<html> 
<body> 
    If everything works, you should see a message here: <h2 id="msg"></h2> 

    <script> 
    var checkpoint1 = true 
    var checkpoint2 = false 
    $(document).ready(function(){ 
     checkpoint2 = true 
     $('#msg').html("It works, it works, it works!") 
    }) 
    </script> 
</body> 
</html> 

和codez:

fs = require('fs'); 
htmlSource = fs.readFileSync("public/examples/test_js_dom.html", "utf8"); 

global.jsdom = require("jsdom"); 

jsdom.defaultDocumentFeatures = { 
    FetchExternalResources : ['script'], 
    ProcessExternalResources : ['script'], 
    MutationEvents   : '2.0', 
    QuerySelector   : false 
}; 

doc = jsdom.jsdom(htmlSource) 
window = doc.createWindow() 
jsdom.jQueryify(window, "http://code.jquery.com/jquery-1.8.3.min.js", function(){ 
    console.log(window.checkpoint1); 
    console.log(window.checkpoint2); 
    console.log(window.$().jquery) 
    console.log("body:"); 
    console.log(window.$('body').html()); 
}); 

和输出:

[email protected]:~/projects/notjs$ test/jsdom.js 
true 
false 
1.8.3 
body: 

     If everything works, you should see a message here: <h2 id="msg"></h2> 

     <script> 
     var checkpoint1 = true 
     var checkpoint2 = false 
     $(document).ready(function(){ 
      checkpoint2 = true 
      $('#msg').html("It works, it works, it works!") 
     }) 
     </script> 
    <script class="jsdom" src="http://code.jquery.com/jquery-1.8.3.min.js"></script> 

我在做什么错?

增加细节以满足荒谬的stackoverflow比率。

[email protected]:~/projects/notjs$ npm ls jsdom 
[email protected] /Users/Bee/projects/notjs 
├─┬ [email protected] 
│ └── [email protected] 
└── [email protected] 
[email protected]:~/projects/notjs$ node -v 
v0.8.15 
[email protected]:~/projects/notjs$ npm -v 
1.1.66 

[解决方法]:

谢谢你,Dave领导我正确的答案。

我认为完整的jsdom答案是这样的;不要使用jsdom.jQuerify,添加脚本标记以在页面脚本上方的页面中加载jQuery(因为它需要为了在浏览器中加载页面)。

HTML:

... 
    If everything works, you should see a message here: <h2 id="msg"></h2> 

    <script src="http://notjs.org/vendor/jquery-1.8.3.min.js"></script> 
    <script> 
     var checkpoint1 = true 
     var checkpoint2 = false 
     $(document).ready(function(){ 
     var checkpoint2 = true 
    ...  

代码:

... 
    doc = jsdom.jsdom(htmlSource) 
    window = doc.createWindow() 
    window.addEventListener('load', function(){ 
     console.log(window.checkpoint1); 
     console.log(window.checkpoint2); 
     console.log(window.$().jquery) 
     console.log("body:"); 
     console.log(window.$('body').html()); 
    }); 
    ... 

回答

1

的jQuery当你的脚本解析首次没有加载,所以$没有定义。这意味着$(document).ready没有定义,所以你的功能没有设置。你应该在控制台中看到这个警告。解决方案是确保jQuery在创建document.ready函数之前已经加载。我不熟悉jsdom,但有两种方法可以解决这个问题:

  1. 将生成的<script>标记移到内联脚本的上方。这可能或不可能与jsdom。
  2. 将您的内联脚本移到jsdom回调中,并在其中拥有所有console.log函数。因为这一点jQuery已被加载。编辑:其实我认为jsdom就像一个预处理器?在这种情况下,这个将不起作用,你需要做(1)。
+0

呃!是的,正确的答案是将脚本标记添加到页面以在页面脚本之前加载jQuery。谢谢! – 2013-03-24 17:16:32

相关问题