CDATA标签在脚本标签中是必要的吗?如果是的话,什么时候?

换句话说,何时何地:

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

更可取的是:

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

当前回答

当您想要验证它时(在XML/XHTML中-感谢Loren Segal)。

其他回答

CDATA告诉浏览器按原样显示文本,而不是将其呈现为HTML。

这是X(HT)ML的问题。当你在JavaScript中使用像<和>这样的符号时,例如比较两个整数,这将不得不像XML一样被解析,因此它们将标记为标记的开始或结束。

CDATA意味着下面的行(直到]]>的所有内容都不是XML,因此不应该以这种方式解析。

不要在HTML4中使用CDATA,但你应该在XHTML中使用CDATA,如果你有像<和>这样的未转义符号,则必须在XML中使用CDATA。

避免在XHTML验证期间出现XML错误。

它可以确保在页面中嵌入JavaScript(而不是外部引用)时XHTML验证能够正确工作。

XHTML要求页面严格符合XML标记要求。由于JavaScript可能包含具有特殊含义的字符,因此必须将其包装在CDATA中,以确保验证不会将其标记为畸形格式。

With HTML pages on the web you can just include the required JavaScript between and tags. When you validate the HTML on your web page the JavaScript content is considered to be CDATA (character data) that is therefore ignored by the validator. The same is not true if you follow the more recent XHTML standards in setting up your web page. With XHTML the code between the script tags is considered to be PCDATA (parsed character data) which is therefore processed by the validator. Because of this, you can't just include JavaScript between the script tags on your page without 'breaking' your web page (at least as far as the validator is concerned).

您可以在这里了解更多关于CDATA的知识,在这里了解更多关于XHTML的知识。