javascript - jQuery HTML 解析器在没有警告的情况下删除了一些标签,为什么以及如何防止它?

标签 javascript jquery html xml

事情是这样的

我有一个充满 HTML 代码的文本区域(ID 为“input_container”),简单的例子是:

<!doctype html>
<html>
    <head></head>
    <body>
        <a href="www.example.com">the other place</a>
    </body>
</html>

我使用 jQuery 解析了它,这是我的代码:

我将所有这些 HTML 字符串放入名为 domString 的变量中,如下所示:

domString = $('#input_container').val();

要获取变量 domString 中所有内容的解析 HTML,我必须用另一个标签将其包装起来,所以我这样做了:

dom = "<allhtml>" + domString + "</allhtml>";

然后让 jQuery 选择器中的所有内容都被解析:

dDom = $(dom);

之后我检查了 dDom 中的内容,所以我做了

alert(dDom.html());

那应该给我标签内的任何东西,对吧?

但不幸的是,我得到的只是:

<a href="www.example.com">the other place</a>

所有其他标签都神秘地消失了。谁能解释这种现象并告诉我如何真正解析所有 DOM?

谢谢

最佳答案

From the jQuery documentation :

When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, we use the browser's .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as <html>, <title>, or <head> elements. As a result, the elements inserted may not be representative of the original string passed.

这应该可以代替:

$('<html />').append($('<head />')).append($('<body />').append($('<a href="www.example.com">the other place</a>')));

虽然这是一件很奇怪的事情,但您可能想考虑其他方法来完成您想要完成的事情,我担心您可能正在遭受 XY Problem 的困扰。 .

关于javascript - jQuery HTML 解析器在没有警告的情况下删除了一些标签,为什么以及如何防止它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8618205/

相关文章:

javascript - 在不丢失 'this' 上下文的情况下将原型(prototype)函数作为参数传递

javascript - 单击按钮不会在 Chrome 中触发 javascript 函数,但在 IE 中工作正常

javascript - 使用setAttribute()添加“onclick”函数

python - xpath 表达式仅获取动态内容节点的文本内容

javascript - WebSQL | SQLite - 将 "?"字符插入数据库

javascript - jQuery 未定义,如果定义,不会被加载?

html - &lt;input type ="text"/>中的多行输入

javascript - 将单选按钮的值存储到 ajax 调用中

android - 如何在平板电脑上禁用 select2 jQuery 插件?

javascript - JSON:通过什么途径访问键值?