本文介绍了如何在Node.js中使用JQuery选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从硬盘中的HTML文件提取电子邮件信息.
I'm trying to extract email info from HTML files in my hard drive.
如果我将文件加载到firefox中并运行jQuerify书签,我可以成功使用以下选择器/功能
If I load the file in firefox and run jQuerify bookmarklet I can use successfully the following selector/function
window.jQuery("a.iEmail").each(function(el) {
console.log(window.jQuery(this).attr('href'))
});
但是在Node.js中使用它不起作用
But using this in Node.js is not working
var document = require("jsdom").jsdom(),
script = document.createElement("script"),
fs = require('fs');
fs.readFile('file_1.html', 'utf-8', function(err, data){
if (err) {
throw err;
}
// This output the document
//console.log(data)
var window = document.createWindow(data);
script.src = 'http://code.jquery.com/jquery-1.4.2.js';
script.onload = function() {
console.log(window.jQuery.fn.jquery);
// outputs: 1.4.2
//console.log(window.jQuery);
/*
* This line works if i load the local file in firefox and execute
* the jQuerify bookmarlet
*/
window.jQuery("a.iEmail").each(function(el) {
console.log(window.jQuery(this).attr('href'))
});
};
document.head.appendChild(script);
});
推荐答案
我现在知道问题出在哪里.
I now know what the problem is.
必须在文档创建调用中传递html数据,因此代码如下所示:
The html data, must be passed in the document creation call, so the code look like this:
var jsdom = require("jsdom"),
fs = require('fs');
fs.readFile('file_1.html', 'utf-8', function(err, data){
if (err) {
throw err;
}
// This output the document
//console.log(data)
// HTML data should be in document creation call
var document = jsdom.jsdom(data); // data is the html content
var script = document.createElement("script");
// HTML data SHOULD NOT be in window creation call
var window = document.createWindow();
script.src = 'http://code.jquery.com/jquery-1.4.2.js';
script.onload = function() {
console.log(window.jQuery.fn.jquery);
// outputs: 1.4.2
//console.log(window.jQuery);
/*
* This line works if i load the local file in firefox and execute
* the jQuerify bookmarlet
*/
window.jQuery("a.iEmail").each(function(el) {
console.log(window.jQuery(this).attr('href'))
});
};
document.head.appendChild(script);
});
这篇关于如何在Node.js中使用JQuery选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!