我将 jsdom 与 jquery 一起使用,并且运行得很好。然而,我试图将我的代码模块化一点,这样我就不会重复自己,所以我用一些 jsdom 代码创建了一个基本函数,它接受一些 html (DOM),用 jquery 调整它,然后将其吐出来。但是,我无法返回结果,因此无法将其分配给调用变量。我可能没有回到正确的地方,但我只是没有看到明显的情况。需要一点帮助。
这是代码:
function tweakIt(html_in){
var jsdom = require('jsdom');
jsdom.env({
html: html_in,
scripts: [
'../public/javascripts/jquery-1.7.1.min.js',
],
done: function(errors, window) {
var $ = window.$;
// do some jquery magic and manipulate the dom
$('body').append('<div>foo</div>');
console.log('Freshly Manipulated HTML: '+ $('body').html()); // it logs perfectly
return $('body').html(); // this isn't returned to where I called tweakIt() from, why not?
}
});
}
var oldhtml = '<html><body><div>some text</div></body></html>';
var newhtml = tweakIt(oldhtml); // never gets set because nothing gets returned, why?
EDIT:
这确实是一个异步问题,因此应该如何使用回调而不是返回来完成它:
function tweakIt(html_in, callback){
var jsdom = require('jsdom');
jsdom.env({
html: html_in,
scripts: [
'../public/javascripts/jquery-1.7.1.min.js',
],
done: function(errors, window) {
var $ = window.$;
// do some jquery magic and manipulate the dom
$('body').append('<div>foo</div>');
console.log('Freshly Manipulated HTML: '+ $('body').html()); // it logs perfectly
callback($('body').html()); // instead of a return, pass the results to the callback
}
});
}
var oldhtml = '<html><body><div>some text</div></body></html>';
var newhtml = tweakIt(oldhtml, function(newstuff){
console.log(newstuff); // woohoo! it works!
});