本文介紹了嘗試使用 DOMParser 解析 html 字符串時遇到的麻煩的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
片段來了:
html = "<!doctype html>";
html += "<html>";
html += "<head><title>test</title></head>";
html += "<body><p>test</p></body>";
html += "</html>";
parser = new DOMParser();
dom = parser.parseFromString (html, "text/html");
嘗試執行這些行時出現錯誤:
here's come the error when trying to execute these lines :
錯誤:組件返回失敗代碼:0x80004001 (NS_ERROR_NOT_IMPLEMENTED) [nsIDOMParser.parseFromString]
我試圖弄清楚發生了什么,但代碼似乎是正確的,我在網上搜索,我來到這里沒有任何線索.
I try to figure out what's going on but the code seems to be right and I searched on the web, i come here with no clues.
您以前遇到過這種故障嗎?如果是,bug 隱藏在哪里?
have you encounter this failure before ? if yes, where's the bug hiding ?
推薦答案
您應該使用 JavaScript DOMParser 訪問 innerHTML 和其他屬性
我為你創建了小提琴 http://jsfiddle.net/CSAnZ/
/*
* DOMParser HTML extension
* 2012-02-02
*
* By Eli Grey, http://eligrey.com
* Public domain.
* NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
*/
/*! @source https://gist.github.com/1129031 */
/*global document, DOMParser*/
(function(DOMParser) {
"use strict";
var DOMParser_proto = DOMParser.prototype
, real_parseFromString = DOMParser_proto.parseFromString;
// Firefox/Opera/IE throw errors on unsupported types
try {
// WebKit returns null on unsupported types
if ((new DOMParser).parseFromString("", "text/html")) {
// text/html parsing is natively supported
return;
}
} catch (ex) {}
DOMParser_proto.parseFromString = function(markup, type) {
if (/^s*text/htmls*(?:;|$)/i.test(type)) {
var doc = document.implementation.createHTMLDocument("")
, doc_elt = doc.documentElement
, first_elt;
doc_elt.innerHTML = markup;
first_elt = doc_elt.firstElementChild;
if (doc_elt.childElementCount === 1
&& first_elt.localName.toLowerCase() === "html") {
doc.replaceChild(first_elt, doc_elt);
}
return doc;
} else {
return real_parseFromString.apply(this, arguments);
}
};
}(DOMParser));
這篇關于嘗試使用 DOMParser 解析 html 字符串時遇到的麻煩的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!