在接受的答案下查看我的评论。基本上,使用该方法存在一些性能问题,这使我寻找更好的方法。为此,我采用了在 rails turbolinks 项目中发现的一种方法,该方法是麻省理工学院许可和编写的咖啡脚本。归功于他们解决了一些浏览器兼容性问题。
https://github.com/rails/turbolinks
/*
* A function that takes a string of HTML and returns a document object.
*/
var parseDocument = (function() {
function createDocumentUsingParser(html) {
return (new DOMParser()).parseFromString(html, 'text/html');
}
function createDocumentUsingDOM(html) {
var doc = document.implementation.createHTMLDocument('');
doc.documentElement.innerHTML = html;
return doc;
}
function createDocumentUsingWrite(html) {
var doc = document.implementation.createHTMLDocument('');
doc.open('replace');
doc.write(html);
doc.close();
return doc;
}
/*
* Use createDocumentUsingParser if DOMParser is defined and natively
* supports 'text/html' parsing (Firefox 12+, IE 10)
*
* Use createDocumentUsingDOM if createDocumentUsingParser throws an exception
* due to unsupported type 'text/html' (Firefox < 12, Opera)
*
* Use createDocumentUsingWrite if:
* - DOMParser isn't defined
* - createDocumentUsingParser returns null due to unsupported type 'text/html' (Chrome, Safari)
* - createDocumentUsingDOM doesn't create a valid HTML document (safeguarding against potential edge cases)
*/
var parser;
if (window.DOMParser) {
try {
var testDoc = createDocumentUsingParser('<html><body><p>test');
if (testDoc && testDoc.body && testDoc.body.childNodes.length === 1) {
parser = createDocumentUsingParser;
}
} catch(ex) {
parser = createDocumentUsingDOM;
}
}
if (!parser) {
parser = createDocumentUsingWrite;
}
return parser;
})();
然后大概例如您可以执行以下操作:
var doc = parseDocument(wadOfHtml);
var title = doc.title;
var $content = $(doc).find('#content');
请注意,我尚未亲自验证此代码是否有效,我将失去 rails 项目的声誉。我也没有验证我对coffeescript 的改编是否没有引入语法或其他错误。我什至还没有运行它。我只是乐观。