2007年5月29日 星期二

JavaScript Basic -1

所有的Javascript碼是包在<script></script>HTML tag之中
它可以放在表頭 (Head) 區, 或是body區,或者是另一個外部檔案中。
當JavaScripts放在body section 時,在載入頁面時即會執行。
當JavaScripts放在 head section 時,只有被呼叫時才會執行。
Javascript儲存為外部檔案時,其副檔名為 .js,通常是多個頁面需要相同JavaScript碼時,使用外部設定便會十分方便,要注意,此外部檔案不需要包括<script></script>HTML tag。
呼叫方式為:
<script src="xxx.js"></script>

要同時在Head或Body區放置多少條JavaScript程式碼是沒有限制的,只要每一段都是包在<script></script>HTML tag之中即可。

基礎指令:
document.write("想要寫出的內容"):是用來寫出到頁面的JavaScript指令。

變數:
宣告方式var strname = some value

變數名稱大小寫是有差異的,即strname與STRNAME是會被視為不同的變數。也可以省掉var,直接指定變數值:
strname = "Hege"
變數的生命週期:若是存在於function內的變數,只要該函數結束,此變數也消失。此種變數稱為local variable。不同函數內的變數可以使用相同名稱也沒關係。若是置於函數外的變數,則會一直存在到頁面結束為止。

條件式:
有以下的條件式設定:

  • if statement - use this statement if you want to execute some code only if a specified condition is true
  • if...else statement - use this statement if you want to execute some code if the condition is true and another code if the condition is false
  • if...else if....else statement - use this statement if you want to select one of many blocks of code to be executed
  • switch statement - use this statement if you want to select one of many blocks of code to be executed
例如:
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>")
}
else if (time>10 && time<16)
{
document.write("<b>Good day!</b>")
}
else
{
document.write("<b>Hello World!</b>")
}
</script>

沒有留言:

Harry

Harry

亭妤

亭妤