special characters in embedded javascript

╄→尐↘猪︶ㄣ 提交于 2019-12-24 08:46:29

问题


I have some javascript that is embedded in the html file like this

<html>
    <head>
        <script>
            // and the script runs here
        </script>
    </head>
    <body></body>
</html>

And it has a line like this

if((os == 'Mac')&&((br == 'Safari')||(br == 'Chrome')))

Everything goes OK (which means the script works), but the validator is screaming:

... character "&" is the first character of a delimiter but occurred as data
... This message may appear in several cases:
-You tried to include the "<" character in your page: you should escape it as "<"
-You used an unescaped ampersand "&": this may be valid in some contexts, but it is recommended to use "&", which is always safe.
-Another possibility is that you forgot to close quotes in a previous tag.

It seems ridiculous to replace all & with &amp. How can I get rid of that error?


回答1:


If you are using XHTML, you need to enclose your inline scripts within a CDATA section:

<script type="text/javascript">
// <![CDATA[
    document.write("&");
// ]]>
</script>

Further reading:

  • About.com: Javascript and XHTML
  • Codehouse.com: Making JavaScript Compatible with XHTML
  • Wikipedia: CDATA


来源:https://stackoverflow.com/questions/2302776/special-characters-in-embedded-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!