簡單說一下業務場景,前台用戶通過input輸入內容,在離開焦點時,將內容在div中顯示。
這時遇到一個問題,如果用戶輸入了html標簽,則在div顯示中,標簽被解析。
由於是純前端操作,不涉及后端,因此需要通過js對輸入內容進行轉義。
這里提供一個非常簡單有效的轉義方案,利用了innerHTML和innerText
注:火狐不支持innerText,需要使用 textContent 屬性,而IE早期版本不支持此屬性,為了同時兼容IE及火狐,需要進行判斷操作。
因為innerText(textContent)會獲取純文本內容,忽略html節點標簽,而innerHTML會顯示標簽內容,
所以我們先將需轉義的內容賦值給innerText(textContent),再獲取它的innerHTML屬性,這時獲取到的就是轉義后文本內容。
代碼如下:
function HTMLEncode(html) { var temp = document.createElement("div"); (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html); var output = temp.innerHTML; temp = null; return output; }
var tagText = "<p><b>123&456</b></p>"; console.log(HTMLEncode(tagText));//<p><b>123&456</b></p>
通過測試結果,可以看到html標簽及&符都被轉義后保存。
同理,反轉義的方法為先將轉義文本賦值給innerHTML,然后通過innerText(textContent)獲取轉義前的文本內容
function HTMLDecode(text) { var temp = document.createElement("div"); temp.innerHTML = text; var output = temp.innerText || temp.textContent; temp = null; return output; }
var tagText = "<p><b>123&456</b></p>"; var encodeText = HTMLEncode(tagText); console.log(encodeText);//<p><b>123&456</b></p> console.log(HTMLDecode(encodeText)); //<p><b>123&456</b></p>
via:https://www.cnblogs.com/yikuu/p/8931943.html