当我通过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>和编解码器:
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());
});和输出:
Bee@cleanroom:~/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>我做错了什么?
将细节添加到令人满意的荒谬堆栈溢出率。
Bee@cleanroom:~/projects/notjs$ npm ls jsdom
notjs@1.0.0 /Users/Bee/projects/notjs
├─┬ jquery@1.8.3
│ └── jsdom@0.2.19
└── jsdom@0.3.3
Bee@cleanroom:~/projects/notjs$ node -v
v0.8.15
Bee@cleanroom:~/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());
});
...发布于 2013-03-25 01:06:55
第一次解析脚本时,jQuery尚未加载,因此未定义$。这意味着没有定义$(document).ready,所以没有设置您的函数。您应该已经在控制台中看到了有关此问题的警告。解决方案是在创建document.ready函数之前确保jQuery已加载。我不熟悉jsdom,但有两种方法可以做到这一点:
<script>标记移到内联脚本的上方。https://stackoverflow.com/questions/15601289
复制相似问题