JavaScript 基础技巧(2)

来源:互联网 发布:正规的网络兼职网站 编辑:程序博客网 时间:2024/06/09 21:14

 

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();”>