例如: 從資料庫抓出了如下的一段 HTML 碼
1 | < b >< font color = "#FF0000" >This is a test</ font ></ b > |
1 2 3 4 | < div id = "divMsg" ></ div > < script type = "text/javascript" > $("#divMsg").html("${msg}"); </ script > |
1 2 3 4 | < div id = "divMsg" ></ div > < script type = "text/javascript" > $("#divMsg").html("< b >< font color = "#FF0000" >This is a test</ font ></ b >"); </ script > |
目前我知道的解法有以下三種: (都需在 Server 端先處理要輸出的文字內容)
- 如果想用 .html("") 設定資料, 就將內容中的雙引號(") 轉換為斜線加雙引號(\"), 使其在 HTML 原始碼上形成如下的結果: 1234
<
div
id
=
"divMsg"
></
div
>
<
script
type
=
"text/javascript"
>
$("#divMsg").html("<
b
><
font
color=\"#FF0000\">This is a test</
font
></
b
>");
</
script
>
- 相對地, 如果是要用單引號設定資料(ex: .html('')), 就將內容中的單引號(') 全轉為斜線加單引號(\'), 使其在 HTML 原始碼上形成如下的結果: 1234
<
div
id
=
"divMsg"
></
div
>
<
script
type
=
"text/javascript"
>
$("#divMsg").html('<
b
><
font
color=\'#FF0000\'>This is a test</
font
></
b
>');
</
script
>
- 另一種是將內容先 encode 過後, 再透過 jQuery 做轉換: 上面的程式碼是透過 JSTL 中的 <c:out> 將內容編碼, 然後再利用 jQuery 產生一個空的 <div/> 去進行轉換.12
var
strMsg =
"<c:out value="
${msg}
"/>"
;
$(
"#divMsg"
).html($(
"<div/>"
).html(strMsg).text());
實際的 HTML 原始碼會是如下的內容:123var
strMsg =
"<b><font color='#FF0000'>This is a test
</font></b>"
;
$(
"#divMsg"
).html($(
"<div/>"
).html(strMsg).text());
沒有留言:
張貼留言