尝试使用 DOMParser 解析 html 字符串时遇到的麻烦
- 作者: 八嘎呀路10086
- 来源: 51数据库
- 2022-10-26
问题描述
片段来了:
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));
推荐阅读
热点文章
检查拆分键盘
0
带有“上一个"的工具栏和“下一个"用于键盘输入AccessoryView
0
Activity 启动时显示软键盘
0
UIWebView 键盘 - 摆脱“上一个/下一个/完成"酒吧
0
在 iOS7 中边缘滑动时,使键盘与 UIView 同步动画
0
我的 iOS 应用程序中的键盘在 iPhone 6 上太高了.如何在 XCode 中调整键盘的分辨率?
0
android:inputType="textEmailAddress";- '@' 键和 '.com' 键?
0
禁用 iPhone 中键盘的方向
0
Android 2.3 模拟器上的印地语键盘问题
0
keyDown 没有被调用
0
