脚本标记中何时需要 CDATA 部分? [英] When is a CDATA section necessary within a script tag?

查看:34
本文介绍了脚本标记中何时需要 CDATA 部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CDATA 标签是否需要在脚本标签中使用?如果需要,什么时候需要?

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>

最好是这样:

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

推荐答案

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

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.

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

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

有关该主题的好文章,请参阅 https://web.archive.org/web/20140304083226/http://javascript.about.com/library/blxhtml.htm

For a good writeup on the subject, see https://web.archive.org/web/20140304083226/http://javascript.about.com/library/blxhtml.htm

这篇关于脚本标记中何时需要 CDATA 部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆