更新时间:2022-12-04 21:27:17
以下字符可能会干扰HTML或Javascript解析器,并应在字符串文字中转义:<> ,',\,
和&
。
在一个使用转义字符的脚本块中,正如您所发现的那样。连接方法(< / scr'+'ipt>'
)可能很难阅读。
In a script block using the escape character, as you found out, works. The concatenation method (</scr' + 'ipt>'
) can be hard to read.
var s = 'Hello <\/script>';
对于HTML中的内联JavaScript,您可以使用实体:
For inline Javascript in HTML, you can use entities:
<div onClick="alert('Hello ">')">click me</div>
演示: http://jsfiddle.net/ThinkingStiff/67RZH/
在< script>
块和内联Javascript是 \uxxxx
,其中 xxxx
是十六进制字符代码。
The method that works in both <script>
blocks and inline Javascript is \uxxxx
, where xxxx
is the hexadecimal character code.
- \\\
>
- \\\>
- \\\"
'
- \\\'
\
- \
&
- \\\&
<
- \u003c
>
- \u003e
"
- \u0022
'
- \u0027
\
- \u005c
&
- \u0026
演示: http://jsfiddle.net/ThinkingStiff/Vz8n7/
HTML:
<div onClick="alert('Hello \u0022>')">click me</div>
<script>
var s = 'Hello \u003c/script\u003e';
alert( s );
</script>