今天在使用富文本框开发时遇到的问题:
在富文本框输入类容,如果类似含有了其他样式,例如加粗,下划线等,在传送数据到后台时样式中的一些符号会被转义,
例如:<会被转义成$lt; 当前端读取数据时,我们在富文本框输入的样式不会生效
例如:
$(document).ready(function(){
var a="<p><span style="font-weight: 700; font-style: italic; text-decoration-line: underline;">2123123123123123</span></p>"
$(".test2").html(a);
})
此时在前端显示为:
这并不是我们想要结果
问题原因:浏览器不能讲转义后的样式自动反转义回来,所以我们需要手动去转义
解决办法:
/*反转义*/
function HTMLDecode(text) {
var temp = document.createElement("div");
temp.innerHTML = text;
var output = temp.innerText || temp.textContent;
temp = null;
return output;
}
现在我们来解决开始的问题:修改js
$(document).ready(function(){
var a="<p><span style="font-weight: 700; font-style: italic; text-decoration-line: underline;">2123123123123123</span></p>"
$(".test2").html(HTMLDecode(a));
})
修改后页面显示结果:
问题解决
上面为反转义,顺便把转义的代码一起发出来:
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;
}