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

换句话说,何时何地:

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

更可取的是:

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

当前回答

它可以确保在页面中嵌入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的知识。

其他回答

这样旧的浏览器就不会解析Javascript代码,页面也不会中断。

向后兼容。一定会喜欢的。

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

它可以确保在页面中嵌入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的知识。

CDATA表示其中的内容不是XML。

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