Why does Javascript ignore single line HTML Comments?

ε祈祈猫儿з 提交于 2019-12-07 08:30:25

问题


I just tried this code on my browser (Chrome 39, Windows 8) :-

<html>
    <body>
        <script>
        <!-- 
            document.write("<h1>Hello</h1>");       
        -->
        </script>
    </body>
</html>

This produces the Header text on the browser. But when I make a slight change- put the HTML comment stuff on a single line,

<html>
    <body>
        <script>
        <!-- document.write("<h1>Hello</h1>");        -->
        </script>
    </body>
</html>

This doesn't display anything. Why is it so? I don't think HTML comments are in the Javascript standards.

p.s. I know how to put javascript comments. I'm only wondering about this erratic behavior.


回答1:


That's the way to hide javascript to browsers that don't recognize the script element. The first line is allways ignored: Hiding script data from user agents

Commenting scripts in JavaScript

The JavaScript engine allows the string "<!--" to occur at the start of a SCRIPT element, and ignores further characters until the end of the line. JavaScript interprets "//" as starting a comment extending to the end of the current line. This is needed to hide the string "-->" from the JavaScript parser.

<SCRIPT type="text/javascript">
<!--  to hide script contents from old browsers
  function square(i) {
    document.write("The call passed ", i ," to the function.","<BR>")
    return i * i
  }
  document.write("The function returned ",square(5),".")
// end hiding contents from old browsers  -->
</SCRIPT>


来源:https://stackoverflow.com/questions/27428277/why-does-javascript-ignore-single-line-html-comments

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