首页 > 解决方案 > Javascript 中的有效注释

问题描述

我正在学习Javascript并遇到了这个:

<head>
<title>Test</title>
<script language="JavaScript">
<!--
document.write("Hi!");
//-->
</script>
</head>

这是一种有效的评论方式吗?为什么要使用它?

标签: javascript

解决方案


这是一个HTML 注释,在脚本中使用这种格式可以追溯到 90 年代,当时一些浏览器不理解 JavaScript,因此我们必须从这些浏览器中隐藏 JS

通常

<script type="text/javascript"><!-- // hide from older browsers
document.write("Yes we have no bananas"); // this will be written if the browser understands JS
// --></script>

它在 JS 中作为注释被忽略,因此内容将被执行

除非代码就在后面<--

<script type="text/javascript">
<!-- document.write("No we have no bananas"); // this will NOT be written since it is treated as a comment in JS too
// --></script>

您将看到结束注释也在 JS 中被注释,因此它不会被视为减号减号大于// -->

JS 中的 VALID 多行注释是

/* these are
   comments */

单行注释是

// here is one comment

来自 MDN 的更多信息

更多来自 SO:使用 HTML 注释标签 <!-- --> 仍然与 JavaScript 代码相关吗?


推荐阅读