简体   繁体   中英

When to use a <![CDATA[ in Javascript

I've some seen some Javascript code containing CDATA. eg below which I copied from 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.

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. 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.

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. 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. Just write HTML and be done with it.

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

CDATA has no meaning in HTML, but in XML it's used to handle characters such as angle brackets and ampersands. I use a CDATA block when I need to include JavaScript in my XSL Transforms.

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." See also: What is CDATA in HTML?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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