getAttribute(“name”)unescapes html?

时间:2012-06-27 10:40:17

标签: javascript html dom

我们有一些自定义JS脚本来处理工具提示,当我们渲染页面时,这些脚本放在dom属性(工具提示)中。

然而,当我尝试检索此工具提示(显示为div)时,字符串javaScript似乎会自动取消属性值。这是正常的行为吗?有没有办法避免这种情况?

我遇到的问题是< email@example.org>变成(无效)html。

复制的例子:

<div tltip ="&lt;text&gt;" id="escaped" />
<div tltip ="<text>"id="notescaped" />

js:

a  = document.getElementById("escaped").getAttribute("tooltip");
b  = document.getElementById("notescaped").getAttribute("tooltip");
a.match("<"); //returns true (unexpected)
a.match("<"); //returns true (expected)
a == b; // returns true (unexpected)

编辑:

澄清我试图显示一个(div)工具提示,我想以某种方式阅读内容,如:  来自dom的"<b> &lt;email@example.com&gt <\b>"并将其显示在div应显示的位置:“&lt; email@example.org>

1 个答案:

答案 0 :(得分:5)

不是“unes​​capes”字符的JavaScript,而是解析实体的HTML解析器。这是预期的行为。

如果您听起来不合逻辑,请告诉我如何在属性中添加双引号和单引号。

<div tltip=""'">          does not work.
<div tltip="&quot;'">     does work.
<div tltip='"&#39;'>      does work.
<div tltip="&quot;&#39;"> does work.

关于编辑过的问题
您不必阅读原始源代码。例如:

<div tltip="&lt;b&gt;test&lt;/b&gt;" id="test"></div>

var output1 = document.getElementById('html');
var output2 = document.getElementById('plain');
var attrValue = document.getElementById('test').getAttribute('tltip');
output1.innerHTML = attrValue;
output2.textContent = attrValue;

将呈现为:

输出1:测试
输出2:&lt; b&gt; test&lt; / b&gt;

旧的IE版本不支持

textContent。跨浏览器兼容的方式是:

output2[document.textContent === null ? 'textContent' : 'innerText'] = attrValue;
// OR
output2.innerHTML = ''; // Empty contents
output2.appendChild(document.createTextNode(attrValue));

如果您仍想解码实体,那么以下内容将起作用:

// <b> -> &lt;b&gt;
function decode(strHTML) {
    var tmp = document.createElement('div');
    tmp.appendChild(document.createTextNode(strHTML));
    return tmp.innerHTML;
}