为什么Javascript忽略单行HTML注释?

Adi*_*tya 4 html javascript comments

我刚在浏览器上试过这段代码(Chrome 39,Windows 8): -

<html>
    <body>
        <script>
        <!-- 
            document.write("<h1>Hello</h1>");       
        -->
        </script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

这会在浏览器上生成标题文本.但是当我稍作修改时 - 将HTML注释内容放在一行上,

<html>
    <body>
        <script>
        <!-- document.write("<h1>Hello</h1>");        -->
        </script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

这不会显示任何内容.为什么会这样?我认为HTML评论不符合Javascript标准.

ps我知道如何把javascript评论.我只是想知道这种不稳定的行为.

Tob*_*ías 5

这是将javascript隐藏到无法识别script元素的浏览器的方法.总是忽略第一行:隐藏来自用户代理的脚本数据

在JavaScript中评论脚本

JavaScript引擎允许字符串"<!--"出现在SCRIPT元素的开头,并 忽略其他字符直到行的结尾.JavaScript解释"//"为开始延伸到当前行末尾的注释.这是"-->"从JavaScript解析器隐藏字符串所必需的.

<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>
Run Code Online (Sandbox Code Playgroud)