编辑:
此答案发布很久以前,并且该
htmlDepre功能引入了XSS漏洞。已对其进行了修改,将临时元素从
div改为
textarea减少了XSS机会。但是如今,我鼓励您使用其他anwswer中建议的DOMParser
API 。
我使用以下功能:
function htmlEnpre(value){ // Create a in-memory element, set its inner text (which is automatically enpred) // Then grab the enpred contents back out. The element never exists on the DOM. return $('<textarea/>').text(value).html();}function htmlDepre(value){ return $('<textarea/>').html(value).text();}基本上,textarea元素是在内存中创建的,但是永远不会附加到文档中。
在
htmlEnpre函数上,我设置的
innerText元素,并检索已编码的
innerHTML;
在
htmlDepre函数上,我设置了
innerHTML元素的值,并
innerText检索到。



