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

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

问题描述



换句话说,何时何地是这样的:

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

优先于此:

 < script type =text / javascript> 
...代码...
< / script>


解决方案

如果您需要文档解析为XML(例如,当XHTML页面被解释为XML时)并且您希望能够写入文字 i <10 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

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

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