<s开发者_运维技巧cript type="text/javascript">
function test() {
alert('<span>blah<span>');
}
</script>
<a href="#" onclick="test();">First</a><br />
<a href="#" onclick="alert('<span>blah<span>');">Second</a><br />
Third: <span>blah<span>
Demo: http://jsfiddle.net/LPYTZ/
Why is the first result different? Are <script>
tags somehow excluded from entity conversion?
In HTML, script and style elements are defined in the DTD as containing CDATA. This means that entities and tags are ignored until the parser hits something that looks like an end tag.
XHTML is different and entities and tags inside those elements function as normal — but only when parsed as XHTML. You can explicitly mark content as CDATA with <![CDATA[ … ]]>
.
Browsers will treat XHTML served as text/html using HTML rules which leads to a big ball of nasty as you try to write code that is correct under both sets of rules.
The simplest way to avoid problems is to keep scripts in external files and use the src
attribute to include them.
Yes, the content model of STYLE
and SCRIPT
is special:
Although the
STYLE
andSCRIPT
elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence "</
" (end-tag open delimiter) is treated as terminating the end of the element's content. In valid documents, this would be the end tag for the element.
精彩评论