2013-03-24 164 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

相關問題