為了程式碼的可讀性,幾乎每種語言都提供了註解功能,JavaScript 也不例外。最常見的有兩種形式。
以 // 開頭,到該行結尾結束。
<html> <head> <title>javascript單行注釋</title> <script language="javascript"> <!-- // The first alert is below alert("An alert triggered by JavaScript!"); // Here is the second alert alert("A second message appears!"); // --> </script> </head> <body> </body> </html>
以 /* 開始、*/ 結束,中間可以跨多行。
<html> <head> <title>javascript多行注釋</title> <script language="javascript"> <!-- /* Below two alert() methods are used to fire up two message boxes - note how the second one fires after the OK button on the first has been clicked */ alert("An alert triggered by JavaScript!"); alert("A second message appears!"); // --> </script> </head> <body> </body> </html>
上面範例中,<script> 裡其實還多包了一層 HTML 註解 <!-- ... -->。這是早期用來「驗證瀏覽器是否支援 JavaScript」的技巧。
原理是:HTML 註解以 <!-- 開始、--> 結束。若把 JavaScript 寫在這段註解裡,對於不支援 JavaScript 的老舊瀏覽器來說,整段內容會被當成註解處理,不會嘗試解析而產生錯誤;支援的瀏覽器則會正常執行。
<html> <head> <title>Hide scripts using comments.</title> <script language="javascript" type="text/javascript"> <!-- document.write("您的浏覽器支持JavaScript腳本!"); //--> </script> </head> <body> Page content here... </body> </html>
注意結尾處的 //-->:前面加上 //,是為了讓支援 JS 的瀏覽器把 --> 當成 JS 註解而不報錯。
補充一句現實情況:這招是網路泡沫時代的產物,如今已完全沒有必要——現代瀏覽器無一不支援 JavaScript,直接把 <script> 寫乾淨就好,多包一層反而干擾閱讀。