开发者

HTML entities inside script tag not converted?

<s开发者_运维技巧cript type="text/javascript">
    function test()    {
        alert('&lt;span&gt;blah&lt;span&gt;');
    }
</script>
<a href="#" onclick="test();">First</a><br />
<a href="#" onclick="alert('&lt;span&gt;blah&lt;span&gt;');">Second</a><br />
Third: &lt;span&gt;blah&lt;span&gt;

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 and SCRIPT 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜