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
323 views
in Technique[技术] by (71.8m points)

javascript - 何时在脚本标记中需要CDATA节?(When is a CDATA section necessary within a script tag?)

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

(脚本标记中是否曾经需要CDATA标记?如果需要,何时?)

In other words, when and where is this:

(换句话说,何时何地:)

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

preferable to this:

(对此更可取:)

<script type="text/javascript">
...code...
</script>
  ask by brad translate from so

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

1 Reply

0 votes
by (71.8m points)

A CDATA section is required if you need your document to parse as XML (eg 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

(如果您需要将文档解析为XML(例如,将XHTML页面解释为XML), 并且希望能够写i<10a && b而不是i&lt;10a &amp;&amp; b ;,则需要CDATA部分a &amp;&amp; b)

a &amp;&amp; b , as XHTML will parse the JavaScript code as parsed character data as opposed to character data by default.

(a &amp;&amp; b ,因为XHTML会将JavaScript代码解析为解析的字符数据,而不是默认的字符数据。)

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中的任何内联JavaScript,您可能都想使用CDATA部分。)

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

(请注意,绝不会将许多XHTML页面解析为XML,在这种情况下,这不会成为问题。)

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

(有关此主题的出色文章,请参见https://web.archive.org/web/20140304083226/http://javascript.about.com/library/blxhtml.htm)


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

...