简体   繁体   English

什么时候用

[英]When to use a <![CDATA[ in Javascript

I've some seen some Javascript code containing CDATA. 我看到一些包含CDATA的Javascript代码。 eg below which I copied from http://www.w3schools.com/xml/xml_cdata.asp 例如,我从http://www.w3schools.com/xml/xml_cdata.asp复制

<script>
    <![CDATA[
    function matchwo(a,b)
    {
    if (a < b && a < 0) then
      {
      return 1;
      }
    else
      {
      return 0;
      }
    }
    ]]>
    </script>

Note that I did a description contained on link above. 请注意,我在上面的链接中做了一个描述。 However I could come to conclusion on when to decide to use the CDATA tag. 但是我可以得出何时决定使用CDATA标签的结论。

If anyone could help me understand the purpose of this tag and when to use it will be great. 如果有人能帮我理解这个标签的用途,那么什么时候使用它会很棒。

In XHTML the content of script elements is treated as markup. 在XHTML中,脚本元素的内容被视为标记。 So < and & have their usual special meaning. 所以<&有其通常的特殊含义。 A CDATA block tells the parser to treat the content as text instead of markup, so you can say if x is less than y without the < being treated as the start of a tag. CDATA块告诉解析器将内容视为文本而不是标记,因此您可以说x是否小于y而不将<视为标记的开头。

Note that if you serve XHTML with a Content-Type of text/html then it will be treated as broken HTML and not as XML. 请注意,如果您使用Content-Type of text/html提供XHTML,那么它将被视为损坏的HTML而不是XML。 I recommend avoiding XHTML - it is only useful if you have XML processors in your tool chain and munging it to play nicely with HTML parsers is unnecessary work. 我建议避免使用XHTML - 只有在工具链中使用XML处理器并将其与HTML解析器很好地配合才是有用的,这是不必要的工作。 Just write HTML and be done with it. 只需编写HTML并完成它。

我们可以说,我们需要CDATA部分,我们需要将您的文档解析为XML

CDATA has no meaning in HTML, but in XML it's used to handle characters such as angle brackets and ampersands. CDATA在HTML中没有任何意义,但在XML中它用于处理尖括号和&符号等字符。 I use a CDATA block when I need to include JavaScript in my XSL Transforms. 当我需要在我的XSL转换中包含JavaScript时,我使用CDATA块。

Understanding what CDATA does will probably help you understand when to use it: "Some text, like JavaScript code, contains a lot of "<" or "&" characters. To avoid errors script code can be defined as CDATA." 了解CDATA的功能可能会帮助您了解何时使用它:“某些文本(如JavaScript代码)包含大量”<“或”&“字符。为避免错误,脚本代码可以定义为CDATA。 See also: What is CDATA in HTML? 另请参阅: HTML中的CDATA是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM