我们有一些自定义JS脚本来处理工具提示,当我们渲染页面时,这些脚本放在dom属性(工具提示)中。
然而,当我尝试检索此工具提示(显示为div)时,字符串javaScript似乎会自动取消属性值。这是正常的行为吗?有没有办法避免这种情况?
我遇到的问题是< email@example.org>变成(无效)html。
复制的例子:
<div tltip ="<text>" 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> <email@example.com> <\b>"
并将其显示在div应显示的位置:“&lt; email@example.org> ”
答案 0 :(得分:5)
不是“unescapes”字符的JavaScript,而是解析实体的HTML解析器。这是预期的行为。
如果您听起来不合逻辑,请告诉我如何在属性中添加双引号和单引号。
<div tltip=""'"> does not work.
<div tltip=""'"> does work.
<div tltip='"''> does work.
<div tltip=""'"> does work.
关于编辑过的问题
您不必阅读原始源代码。例如:
<div tltip="<b>test</b>" 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;
textContent
。跨浏览器兼容的方式是:
output2[document.textContent === null ? 'textContent' : 'innerText'] = attrValue;
// OR
output2.innerHTML = ''; // Empty contents
output2.appendChild(document.createTextNode(attrValue));
如果您仍想解码实体,那么以下内容将起作用:
// <b> -> <b>
function decode(strHTML) {
var tmp = document.createElement('div');
tmp.appendChild(document.createTextNode(strHTML));
return tmp.innerHTML;
}