我们有一些自定义的 JS 脚本来处理工具提示,当我们呈现页面时,这些脚本被放在 dom 属性(工具提示)中。
然而,当我尝试检索此工具提示(显示为 div)字符串时,javaScript 似乎自动取消转义属性值。这是正常行为吗?有没有办法避免这种情况?
我遇到的问题是
复制示例:
<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) 工具提示,我想以某种方式阅读内容,例如:
"<b> <email@example.com> <\b>"
从 dom 并将其显示在 div 中,它应该如下所示:“
最佳答案
“取消转义”字符的不是 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:测试
textContent
在旧的 IE 版本中不受支持。一种跨浏览器兼容的方式是:
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;
}
关于javascript - getAttribute ("name") 转义 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11224362/