我正在编写一些需要解析大量包含 HTML 片段的文件的代码。看起来 jQuery 对此非常有用,但是当我尝试将 jQuery 加载到 WScript 或 CScript 之类的内容中时,由于 jQuery 对窗口对象的许多引用,它会抛出错误。
有什么实用的方法可以在无需浏览器的情况下运行的代码中使用 jQuery?
Update:为了响应评论,我已经成功编写了 JavaScript 代码来使用以下命令读取文件内容new ActiveXObject('Scripting.FileSystemObject');
。我知道 ActiveX 是邪恶的,但这只是一个内部项目,目的是从一些包含 HTML 片段的文件中获取一些数据并将其放入适当的数据库中。
另一个更新:到目前为止我的代码看起来像这样:
var fileIo, here;
fileIo = new ActiveXObject('Scripting.FileSystemObject');
here = unescape(fileIo.GetParentFolderName(WScript.ScriptFullName) + "\\");
(function() {
var files, thisFile, thisFileName, thisFileText;
for (files = new Enumerator(fileIo.GetFolder(here).files); !files.atEnd(); files.moveNext()) {
thisFileName = files.item().Name;
thisFile = fileIo.OpenTextFile(here + thisFileName);
thisFileText = thisFile.ReadAll();
// I want to do something like this:
s = $(thisFileText).find('input#txtFoo').val();
}
})();
Update:我也在 jQuery 论坛上发布了这个问题:http://forum.jquery.com/topic/how-to-use-jquery-without-a-browser#14737000003719577 http://forum.jquery.com/topic/how-to-use-jquery-without-a-browser#14737000003719577
按照您的代码,您可以使用 Windows Script Host 创建 IE 实例,将 html 文件加载到该实例中,将 jQuery 动态附加到加载的页面,然后从中编写脚本。
这适用于 IE8 和 XP,但我知道 Windows 7/IE9 中存在一些安全问题。如果您遇到问题可以尝试降低您的安全设置 https://stackoverflow.com/questions/6661005/error-the-object-invoked-has-disconnected-from-its-clients-automate-ie-8-wit.
var fileIo, here, ie;
fileIo = new ActiveXObject('Scripting.FileSystemObject');
here = unescape(fileIo.GetParentFolderName(WScript.ScriptFullName) + "\\");
ie = new ActiveXObject("InternetExplorer.Application");
ie.visible = true
function loadDoc(src) {
var head, script;
ie.Navigate(src);
while(ie.busy){
WScript.sleep(100);
}
head = ie.document.getElementsByTagName("head")[0];
script = ie.document.createElement('script');
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js";
head.appendChild(script);
return ie.document.parentWindow;
}
(function() {
var files, thisFile, win;
for (files = new Enumerator(fileIo.GetFolder(here).files); !files.atEnd(); files.moveNext()) {
thisFile = files.item();
if(fileIo.GetExtensionName(thisFile)=="htm") {
win = loadDoc(thisFile);
// your jQuery reference = win.$
WScript.echo(thisFile + ": " + win.$('input#txtFoo').val());
}
}
})();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)