Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

javascript - HTML entities inside script tag not converted?

<script 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...