兼容IE和FF的JS HTMLEncode和HTMLDecode的完整實例,因為這個在在線編輯器和Ajax中經(jīng)常用到,所以封裝成函數(shù)可以直接調(diào)用,希望對大家有幫助。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8" />
<title>HTMLEcode</title>
</head>
<body>
方法一:<BR>
<BR>
用的瀏覽器內(nèi)部轉(zhuǎn)換器實現(xiàn)轉(zhuǎn)換,方法是動態(tài)創(chuàng)建一個容器標簽元素,如DIV,將要轉(zhuǎn)換的字符串設(shè)置為這個元素的innerText(ie支持) ||textContent(火狐支持),然后返回這個元素的innerHTML,即得到經(jīng)過HTML編碼轉(zhuǎn)換的字符串,顯示的時候反過來就可以了(實際 上顯示的時候不用通過轉(zhuǎn)換,直接賦值在div就可以正常顯示的)。
<script type="text/javascript">
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;
}
function HTMLDecode(text)
{
var temp = document.createElement("div");
temp.innerHTML = text;
var output = temp.innerText || temp.textContent;
temp = null;
return output;
}
var html = "<br>dffdf<p>qqqqq</p>";
var encodeHTML = HTMLEncode(html);
alert("方式一:" + encodeHTML);
var decodeHTML = HTMLDecode(encodeHTML);
alert("方式一:" + decodeHTML);
</script>
方法二:<BR>
<BR>
通過把正則表達式把<>和空格符轉(zhuǎn)換成html編碼,由于這種方式不是系統(tǒng)內(nèi)置的所以很容易出現(xiàn)有些特殊標簽沒有替換的情況,而且效率低下
<script type="text/javascript">
function HTMLEncode2(str)
{
var s = "";
if(str.length == 0) return "";
s = str.replace(/&/g,"&");
s = s.replace(/</g,"<");
s = s.replace(/>/g,">");
s = s.replace(/ /g," ");
s = s.replace(/\'/g,"'");
s = s.replace(/\"/g,""");
return s;
}
function HTMLDecode2(str)
{
var s = "";
if(str.length == 0) return "";
s = str.replace(/&/g,"&");
s = s.replace(/</g,"<");
s = s.replace(/>/g,">");
s = s.replace(/ /g," ");
s = s.replace(/'/g,"\'");
s = s.replace(/"/g,"\"");
return s;
}
var html = "<br>ccccc<p>aaaaa</p>";
var encodeHTML = HTMLEncode2(html);
alert("方式二:" + encodeHTML);
var decodeHTML = HTMLDecode2("方式二:" + encodeHTML);
alert(decodeHTML);
</script>
</body>
</html>
如對本文有疑問,請?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會為你解答!! 點擊進入論壇