如何使用.innerHTML编码标签
数组编码html实体
效果不佳
var find = ['<','>','"'];
var replace = ['<','>','"'];
window.onload = function() {
var code = document.getElementsByTagName("code");
cl = code.length;
for (var e = 0; e < cl; e++)
code[e].innerHTML = code[e].innerHTML.replace(find,replace);
};
答案 0 :(得分:1)
创建文本节点更安全。任何需要的逃脱都将为您完成:
window.onload = function() {
var code = document.getElementsByTagName("code");
cl = code.length;
for (var e = 0; e < cl; e++) {
var tx = code[e].innerHTML;
code[e].innerHTML = "";
var n = document.createTextNode(tx);
code[e].appendChild(n);
}
};
<p><code>Escaped: <b><i>foo</i></b></code></p>
<p>Not: <b><i>foo</i></b></p>