JavaScript 基礎技巧(2)

 

14 分割字符串

1: <script language=”JavaScript”>
2: <!--
3: var
 myVariable = “a,b,c,d”;
4: 
var stringArray = myVariable.split(“,”);
5: document.write(stringArray[0
]);
6: document.write(stringArray[1
]);
7: document.write(stringArray[2
]);
8: document.write(stringArray[3
]);
9: 
// -->
10: </script>

15 彈出警告信息

1: <script language=”JavaScript”>
2: <!--
3
: window.alert(“Hello”);
4: 
// -->
5: </script>

16 彈出確認框

1: <script language=”JavaScript”>
2: <!--
3: var result = window.confirm(“Click OK to continue
”);
4: 
// -->
5: </script>

17 定義函數

1: <script language=”JavaScript”>
2: <!--
3: function
 multiple(number1,number2) 
4: var
 result = number1 * number2;
5: 
return result;
6: }
7: // -->
8: </script>

18 調用JS函數

1: <a href=”#” onClick=”functionName()”>Link text</a>
2: <a href="/”javascript:functionName"()”>Link text</a>

19 在頁面加載完成後執行函數

1: <body onLoad=”functionName();”>
2: Body of the page
3: 
</body>


20 條件判斷

1: <script>
2: <!--
3: var
 userChoice = window.confirm(“Choose OK or Cancel”);
4: 
var result = (userChoice == true) ? “OK” : “Cancel”;
5
: document.write(result);
6: 
// -->
7: </script>

21 指定次數循環

1: <script>
2: <!--
3: var myArray = new
 Array(3);
4: myArray[0] = “Item 0
”;
5: myArray[1] = “Item 1
”;
6: myArray[2] = “Item 2
”;
7: 
for (i = 0; i < myArray.length; i++) 
8: document.write(myArray[i] + “<br/>
”);
9: }
10: // -->
11: </script>

22 設定將來執行

1: <script>
2: <!--
3: function
 hello() 
4
: window.alert(“Hello”);
5: }
6: window.setTimeout(“hello()”,5000);
7: 
// -->
8: </script>

 

23 定時執行函數

1: <script>
2: <!--
3: function
 hello() 
4
: window.alert(“Hello”);
5: window.setTimeout(“hello()”,5000
);
6: }
7: window.setTimeout(“hello()”,5000);
8: 
// -->
9: </script>

24 取消定時執行

1: <script>
2: <!--
3: function
 hello() 
4
: window.alert(“Hello”);
5: }
6: var myTimeout = window.setTimeout(“hello()”,5000);
7
: window.clearTimeout(myTimeout);
8: 
// -->
9: </script>

25 在頁面卸載時候執行函數

1: 
2: Body of the page
3: 
</body>

 

<body onUnload=”functionName();”>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章