Ces*_*sar 8 jquery jquery-selectors node.js
我正在尝试从硬盘驱动器中的HTML文件中提取电子邮件信息.
如果我在firefox中加载文件并运行jQuerify bookmarklet,我可以成功使用以下选择器/函数
window.jQuery("a.iEmail").each(function(el) {
console.log(window.jQuery(this).attr('href'))
});
Run Code Online (Sandbox Code Playgroud)
但是在Node.js中使用它是行不通的
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);
});
Run Code Online (Sandbox Code Playgroud)
Ces*_*sar 11
我现在知道问题所在.
html数据必须在文档创建调用中传递,因此代码如下所示:
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);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11383 次 |
| 最近记录: |