为什么Javascript忽略单行HTML注释? [英] Why does Javascript ignore single line HTML Comments?
问题描述
< html>我的浏览器(Chrome 39,Windows 8)
< body>
< script>
<! -
document.write(< h1> Hello< / h1>);
- >
< / script>
< / body>
< / html>
这会在浏览器上生成标题文本。但是,当我稍作改动时,将HTML注释放在一行上,
< html>
< body>
< script>
<! - document.write(< h1> Hello< / h1>); - >
< / script>
< / body>
< / html>
这不会显示任何内容。
为何如此?我不认为HTML标注符合Javascript标准。
p.s。我知道如何把JavaScript评论。我只是想知道这种不稳定的行为。
这是将javascript隐藏到浏览器的方式, code> script 元素。第一行忽略:隐藏用户代理的脚本数据
在JavaScript中评论脚本
JavaScript引擎允许字符串
<! -
出现在SCRIPT
元素的开头,
直到行尾忽略更多字符。 JavaScript解释//
作为开始注释,延伸到
当前行的结尾。这需要隐藏来自
JavaScript解析器的字符串- >
。< SCRIPT type =text / javascript>
<! - 隐藏旧版浏览器的脚本内容
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来自旧浏览器的内容 - >
< / SCRIPT>
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.
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 aSCRIPT
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>
这篇关于为什么Javascript忽略单行HTML注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!