如何在Windows脚本宿主中使用jQuery?

我正在研究一些需要解析包含HTML片段的文件的代码。 似乎jQuery对此非常有用,但是当我尝试将jQuery加载到WScript或CScript之类的东西时,由于jQuery对窗口对象的许多引用,它会抛出错误。

在没有浏览器的情况下运行的代码中使用jQuery有什么实用的方法?

更新:为了回应这些评论,我成功编写了JavaScript代码,使用new ActiveXObject('Scripting.FileSystemObject');读取文件的内容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(); } })(); 

更新:我也在jQuery论坛上发布了这个问题: http : //forum.jquery.com/topic/how-to-use-jquery-without-a-browser#14737000003719577

继您的代码之后,您可以使用Windows脚本宿主创建IE实例,将html文件加载到实例中,将jQuery动态地附加到已加载的页面,然后从中添加脚本。

这适用于带有XP的IE8,但我知道Windows 7 / IE9中存在一些安全问题。 如果您遇到问题,可以尝试降低安全设置 。

 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()); } } })(); 

使用cheerio包在Node.js中很容易做到这一点。 你可以从你想要的任何源读取任意HTML,用cheerio解析它,然后使用jQuery样式选择器访问解析的元素。