且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在脚本标记中何时需要CDATA部分?

更新时间:2023-12-05 22:45:04

如果您需要文档解析为XML(例如,当XHTML页面被解释为XML时)并且您希望能够写入文字 i 和 a &安培;&安培; b 而不是 i& lt; 10 a& amp; amp; amp; amp; amp; amp; b ,因为默认情况下,XHTML会将JavaScript代码解析为分析字符数据,而不是字符数据。这不是存储在外部源文件中的脚本的问题,但对于XHTML中的任何内联JavaScript,您可能要使用CDATA部分。



请注意,许多XHTML页面从未打算作为XML解析,在这种情况下,这不会成为问题。



请参阅 http://javascript.about.com/library/blxhtml.htm


Are CDATA tags ever necessary in script tags and if so when?

In other words, when and where is this:

<script type="text/javascript">
//<![CDATA[
...code...
//]]>
</script>

preferable to this:

<script type="text/javascript">
...code...
</script>

A CDATA section is required if you need your document to parse as XML (e.g. when an XHTML page is interpreted as XML) and you want to be able to write literal i<10 and a && b instead of i&lt;10 and a &amp;&amp; b, as XHTML will parse the JavaScript code as parsed character data as opposed to character data by default. This is not an issue with scripts that are stored in external source files, but for any inline JavaScript in XHTML you will probably want to use a CDATA section.

Note that many XHTML pages were never intended to be parsed as XML in which case this will not be an issue.

For a good writeup on the subject, see http://javascript.about.com/library/blxhtml.htm