https://codepen.io/doudoumao/pen/NWBoWJE
说白了就是浏览器解析HTML语法元素时(我们平时写的HTML文件,也是outerHTML/innerHTML),为了保证结构正确不能产生歧义,需转义
概念:
Element.innerHTML 属性设置或获取 HTML 语法表示的元素的后代。
innerHTML表示的是dom结构树,其中字符串片段不能直接使用HTML语法字符,
和号(&)、双引号(")、小于号(<)和大于号(>)特殊符号如需要转译。
场景:
内部文本,html属性
<input type="button" value="Click Me" οnclick="console.log("Clicked")"/>
对照表:
字符 | 十进制 | 转义字符 |
" | " | " |
& | & | & |
< | < | < |
> | > | > |
不断开空格(non-breaking space) |
| |
var HtmlUtil = {
htmlEncode: function (html) {
var temp = document.createElement("div");
(temp.textContent != undefined) ? (temp.textContent = html) : (temp.innerText = html);
var output = temp.innerHTML;
temp = null;
return output;
},
htmlDecode: function (text) {
var temp = document.createElement("div");
temp.innerHTML = text;
var output = temp.innerText || temp.textContent;
temp = null;
return output;
}
}