简体   繁体   English

如何在 cdata 中正确使用方括号

[英]How do I correctly use square bracket with cdata

This is how my code gets shown in my developer console (Chrome):这是我的代码在我的开发者控制台 (Chrome) 中显示的方式:

<script type="text/javascript">// <!&#091;CDATA&#091;
function hidden(){ 
    document.getElementById("test123").style.visibility = "hidden"; 
} 

document.getElementById("test123").addEventListener("click", hidden);

var banner =document.querySelectorAll('.contactBanner1');
for(var i=0;i<banner.length;i++){ 
    banner&#091;i&#093;.addEventListener('mouseover',hidden,false); 
}
// &#093;&#093;></script>

This is the error I get now: Uncaught SyntaxError: Unexpected token ILLEGAL这是我现在得到的错误: Uncaught SyntaxError: Unexpected token ILLEGAL

How do I correctly use the [ ?如何正确使用[

Back when XML was all the rage, people spent a lot of time thinking about their XHTML and XML being parsed by a single XML parser.回到 XML 风靡一时的时候,人们花了很多时间思考他们的 XHTML 和 XML 由单个 XML 解析器解析。 As such, the XHTML needed to pass XML validation.因此,XHTML 需要通过 XML 验证。

But, a problem that can be encountered is when that XHTML includes JavaScript and that JavaScript contains, say, a < meant to mean less-than.但是,可能会遇到的一个问题是,当 XHTML 包含 JavaScript 而 JavaScript 包含例如 < 表示小于时。

In HTML, XHTML and XML the < means beginning of a start or end tag.在 HTML、XHTML 和 XML 中,< 表示开始或结束标记的开始。

To prevent this, it was recommended that scripts in XHTML have their content marked as Character Data, so that if/when the XML parser got to it, it would effectively ignore special symbols like < (among others).为了防止这种情况,建议将 XHTML 中的脚本的内容标记为字符数据,这样如果/当 XML 解析器到达它时,它会有效地忽略诸如 <(等等)之类的特殊符号。

So, scripts should have been written as:所以,脚本应该写成:

 <script type="text/javascript">
   //<![CDATA[ 
           // Inside the CDATA < gets ignored


  //]]>
 </script>

Your code doesn't follow this, instead you are providing the Unicode characters for [ and ].您的代码不遵循此,而是为 [ 和 ] 提供 Unicode 字符。

And, lastly, if you are not worried about your JavaScript being parsed as XML, you can just write the more modern version:最后,如果您不担心您的 JavaScript 被解析为 XML,您可以编写更现代的版本:

 <script>


 </script>

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

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