最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Commenting in JavaScript - Stack Overflow

programmeradmin3浏览0评论

What is the purpose of using // in the following code. If old browsers doesnt support javascript then the symbols <!-- --> will ignore js code. In case browsers support JS, these symbols <!-- --> will be ignored. Then wats the use of // symbols.

<html>
<body>
<script type="text/javascript">
<!--
document.getElementById("demo").innerHTML=Date();
//-->
</script>
</body>
</html>  

What is the purpose of using // in the following code. If old browsers doesnt support javascript then the symbols <!-- --> will ignore js code. In case browsers support JS, these symbols <!-- --> will be ignored. Then wats the use of // symbols.

<html>
<body>
<script type="text/javascript">
<!--
document.getElementById("demo").innerHTML=Date();
//-->
</script>
</body>
</html>  
Share Improve this question asked Feb 8, 2012 at 15:22 sandboxsandbox 2,6819 gold badges35 silver badges39 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 7

If old browsers doesnt support javascript then the symbols <!-- --> will ignore js code.

True, assuming HTML and for a definition of "old browsers" equal to "Netscape 1 era". Don't use them today.

In case browsers support JS, these symbols <!-- --> will be ignored.

Only half true. Only the start of the ment is special cased. From the specification:

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 ment extending to the end of the current line. This is needed to hide the string "-->" from the JavaScript parser.

-- is a JavaScript operator. It is used not to confuse the parser.

You really don't need those HTML ments anymore, BTW.

This is a non-standard feature that browsers and JavaScript engines have always implemented. Nowadays, it cannot be removed, as that would break backwards patibility. It’s detailed in the JavaScript / Web ECMAScript spec:

<!-- must be treated as the start of a SingleLineComment — equivalent to //.

var x = true;
<!-- x = false; // note: no syntax error
x; // true

--> at the start of a line, optionally preceded by whitespace or MultiLineComments, must be treated as a SingleLineComment — equivalent to //.

var x = true;
--> x = false; // note: no syntax error
x; // true

var x = 1;
/*
multiline ment!
x = 2;
*/ --> x = 3;
x; // 1

See HTML Comments and JavaScript

they are also use so that old versions of netscape dont through errors: http://www.yourhtmlsource./javascript/basicjavascript.html

发布评论

评论列表(0)

  1. 暂无评论