JavaScript的方法和技巧

sunnylovecmc發表於2010-01-20

JavaScript的方法和技巧 收藏
有些時候你精通一門語言,但是會發現你其實整天在和其它語言打交道,也許你以為這些微不足道,不至於影響你的開發進度,但恰恰是這些你不重視的東西會浪費 你很多時間,我一直以為我早在幾年前就已經精通JavaScript了,直到目前,我才越來越覺得JavaScript遠比我想象的複雜和強大,我開始崇 拜它,
趁著節日的空隙,把有關JavaScript的方法和技巧整理下,讓每個在為JavaScript而煩惱的人明白,JavaScript就這麼回事!並希望JavaScript還可以成為你的朋友,讓你豁然開朗,在專案中更好的應用~

適合閱讀範圍:對JavaScript一無所知~離精通只差一步之遙的人
基礎知識:HTML


JavaScript就這麼回事1:基礎知識

1 建立指令碼塊

1: <script language=”JavaScript”>
2: JavaScript code goes here
3: </script>

 

2 隱藏指令碼程式碼

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


在不支援JavaScript的瀏覽器中將不執行相關程式碼

3 瀏覽器不支援的時候顯示

1: <noscript>
2: Hello to the non-JavaScript browser.
3: </noscript>

 

4 連結外部指令碼檔案

1: <script language=”JavaScript” src="/”filename.js"”></script>


5 註釋指令碼

1: // This is a comment
2: document.write(“Hello”); // This is a comment
3: /*
4: All of this
5: is a comment
6: */

 

6 輸出到瀏覽器

1: document.write(“<strong>Hello</strong>”);

 

7 定義變數

1: var myVariable = “some value”;

 

8 字串相加

1: var myString = “String1” + “String2”;

 

9 字串搜尋

1: <script language=”JavaScript”>
2: <!--
3: var myVariable = “Hello there”;
4: var therePlace = myVariable.search(“there”);
5: document.write(therePlace);
6: // -->
7: </script>

 

10 字串替換

1: thisVar.replace(“Monday”,”Friday”);


11 格式化字串

1: <script language=”JavaScript”>
2: <!--
3: var myVariable = “Hello there”;
4: document.write(myVariable.big() + “<br/>”);
5: document.write(myVariable.blink() + “<br/>”);
6: document.write(myVariable.bold() + “<br/>”);
7: document.write(myVariable.fixed() + “<br/>”);
8: document.write(myVariable.fontcolor(“red”) + “<br/>”);
9: document.write(myVariable.fontsize(“18pt”) + “<br/>”);
10: document.write(myVariable.italics() + “<br/>”);
11: document.write(myVariable.small() + “<br/>”);
12: document.write(myVariable.strike() + “<br/>”);
13: document.write(myVariable.sub() + “<br/>”);
14: document.write(myVariable.sup() + “<br/>”);
15: document.write(myVariable.toLowerCase() + “<br/>”);
16: document.write(myVariable.toUpperCase() + “<br/>”);
17:
18: var firstString = “My String”;
19: var finalString = firstString.bold().toLowerCase().fontcolor(“red”);
20: // -->
21: </script>

 

12 建立陣列

1: <script language=”JavaScript”>
2: <!--
3: var myArray = new Array(5);
4: myArray[0] = “First Entry”;
5: myArray[1] = “Second Entry”;
6: myArray[2] = “Third Entry”;
7: myArray[3] = “Fourth Entry”;
8: myArray[4] = “Fifth Entry”;
9: var anotherArray = new Array(“First Entry”,”Second Entry”,”Third Entry”,”Fourth Entry”,”Fifth Entry”);
10: // -->
11: </script>

 

13 陣列排序

1: <script language=”JavaScript”>
2: <!--
3: var myArray = new Array(5);
4: myArray[0] = “z”;
5: myArray[1] = “c”;
6: myArray[2] = “d”;
7: myArray[3] = “a”;
8: myArray[4] = “q”;
9: document.write(myArray.sort());
10: // -->
11: </script>

 

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: <body onUnload=”functionName();”>
2: Body of the page
3: </body>

JavaScript就這麼回事2:瀏覽器輸出


26 訪問document物件

1: <script language=”JavaScript”>
2: var myURL = document.URL;
3: window.alert(myURL);
4: </script>

 

27 動態輸出HTML

1: <script language=”JavaScript”>
2: document.write(“<p>Here’s some information about this document:</p>”);
3: document.write(“<ul>”);
4: document.write(“<li>Referring Document: “ + document.referrer + “</li>”);
5: document.write(“<li>Domain: “ + document.domain + “</li>”);
6: document.write(“<li>URL: “ + document.URL + “</li>”);
7: document.write(“</ul>”);
8: </script>


28 輸出換行

1: document.writeln(“<strong>a</strong>”);
2: document.writeln(“b”);

 

29 輸出日期

1: <script language=”JavaScript”>
2: var thisDate = new Date();
3: document.write(thisDate.toString());
4: </script>

 

30 指定日期的時區

1: <script language=”JavaScript”>
2: var myOffset = -2;
3: var currentDate = new Date();
4: var userOffset = currentDate.getTimezoneOffset()/60;
5: var timeZoneDifference = userOffset - myOffset;
6: currentDate.setHours(currentDate.getHours() + timeZoneDifference);
7: document.write(“The time and date in Central Europe is: “ + currentDate.toLocaleString());
8: </script>


31 設定日期輸出格式

1: <script language=”JavaScript”>
2: var thisDate = new Date();
3: var thisTimeString = thisDate.getHours() + “:” + thisDate.getMinutes();
4: var thisDateString = thisDate.getFullYear() + “/” + thisDate.getMonth() + “/” + thisDate.getDate();
5: document.write(thisTimeString + “ on “ + thisDateString);
6: </script>


32 讀取URL引數

1: <script language=”JavaScript”>
2: var urlParts = document.URL.split(“?”);
3: var parameterParts = urlParts[1].split(“&”);
4: for (i = 0; i < parameterParts.length; i++) {
5: var pairParts = parameterParts[i].split(“=”);
6: var pairName = pairParts[0];
7: var pairValue = pairParts[1];
8: document.write(pairName + “ :“ +pairValue );
9: }
10: </script>

你還以為HTML是無狀態的麼?

33 開啟一個新的document物件

1: <script language=”JavaScript”>
2: function newDocument() {
3: document.open();
4: document.write(“<p>This is a New Document.</p>”);
5: document.close();
6: }
7: </script>

 

34 頁面跳轉

1: <script language=”JavaScript”>
2: window.location = “http://www.liu21st.com/”;
3: </script>

 

35 新增網頁載入進度視窗

1: <html>
2: <head>
3: <script language='javaScript'>
4: var placeHolder = window.open('holder.html','placeholder','width=200,height=200');
5: </script>
6: <title>The Main Page</title>
7: </head>
8: <body onLoad='placeHolder.close()'>
9: <p>This is the main page</p>
10: </body>
11: </html>

JavaScript就這麼回事3:影象

 

36 讀取影象屬性

1: <img src="/”image1.jpg"” name=”myImage”>
2: <a href=”# ” onClick=”window.alert(document.myImage.width)”>Width</a>
3:


37 動態載入影象

1: <script language=”JavaScript”>
2: myImage = new Image;
3: myImage.src = “Tellers1.jpg”;
4: </script>


38 簡單的影象替換

1: <script language=”JavaScript”>
2: rollImage = new Image;
3: rollImage.src = “rollImage1.jpg”;
4: defaultImage = new Image;
5: defaultImage.src = “image1.jpg”;
6: </script>
7: <a href="/”myUrl"” onMouseOver=”document.myImage.src = rollImage.src;”
8: onMouseOut=”document.myImage.src = defaultImage.src;”>
9: <img src="/”image1.jpg"” name=”myImage” width=100 height=100 border=0>


39 隨機顯示影象

1: <script language=”JavaScript”>
2: var imageList = new Array;
3: imageList[0] = “image1.jpg”;
4: imageList[1] = “image2.jpg”;
5: imageList[2] = “image3.jpg”;
6: imageList[3] = “image4.jpg”;
7: var imageChoice = Math.floor(Math.random() * imageList.length);
8: document.write(‘<img src=”’ + imageList[imageChoice] + ‘“>’);
9: </script>


40 函式實現的影象替換

1: <script language=”JavaScript”>
2: var source = 0;
3: var replacement = 1;
4: function createRollOver(originalImage,replacementImage) {
5: var imageArray = new Array;
6: imageArray[source] = new Image;
7: imageArray[source].src = originalImage;
8: imageArray[replacement] = new Image;
9: imageArray[replacement].src = replacementImage;
10: return imageArray;
11: }
12: var rollImage1 = createRollOver(“image1.jpg”,”rollImage1.jpg”);
13: </script>
14: <a href=”#” onMouseOver=”document.myImage1.src = rollImage1[replacement].src;”
15: onMouseOut=”document.myImage1.src = rollImage1[source].src;”>
16: <img src="/”image1.jpg"” width=100 name=”myImage1” border=0>
17: </a>


41 建立幻燈片

1: <script language=”JavaScript”>
2: var imageList = new Array;
3: imageList[0] = new Image;
4: imageList[0].src = “image1.jpg”;
5: imageList[1] = new Image;
6: imageList[1].src = “image2.jpg”;
7: imageList[2] = new Image;
8: imageList[2].src = “image3.jpg”;
9: imageList[3] = new Image;
10: imageList[3].src = “image4.jpg”;
11: function slideShow(imageNumber) {
12: document.slideShow.src = imageList[imageNumber].src;
13: imageNumber += 1;
14: if (imageNumber < imageList.length) {
15: window.setTimeout(“slideShow(“ + imageNumber + “)”,3000);
16: }
17: }
18: </script>
19: </head>
20: <body onLoad=”slideShow(0)”>
21: <img src="/”image1.jpg"” width=100 name=”slideShow”>


42 隨機廣告圖片

1: <script language=”JavaScript”>
2: var imageList = new Array;
3: imageList[0] = “image1.jpg”;
4: imageList[1] = “image2.jpg”;
5: imageList[2] = “image3.jpg”;
6: imageList[3] = “image4.jpg”;
7: var urlList = new Array;
8: urlList[0] = “http://some.host/”;
9: urlList[1] = “http://another.host/”;
10: urlList[2] = “http://somewhere.else/”;
11: urlList[3] = “http://right.here/”;
12: var imageChoice = Math.floor(Math.random() * imageList.length);
13: document.write(‘<a href=”’ + urlList[imageChoice] + ‘“><img src=”’ + imageList[imageChoice] + ‘“></a>’);
14: </script>

JavaScript就這麼回事4:表單


還是先繼續寫完JS就這麼回事系列吧~
43 表單構成

1: <form method=”post” action=”target.html” name=”thisForm”>
2: <input type=”text” name=”myText”>
3: <select name=”mySelect”>
4: <option value=”1”>First Choice</option>
5: <option value=”2”>Second Choice</option>
6: </select>
7: <br/>
8: <input type=”submit” value=”Submit Me”>
9: </form>


44 訪問表單中的文字框內容

1: <form name=”myForm”>
2: <input type=”text” name=”myText”>
3: </form>
4: <a href='#' onClick='window.alert(document.myForm.myText.value);'>Check Text Field</a>


45 動態複製文字框內容

1: <form name=”myForm”>
2: Enter some Text: <input type=”text” name=”myText”><br/>
3: Copy Text: <input type=”text” name=”copyText”>
4: </form>
5: <a href=”#” onClick=”document.myForm.copyText.value =
6: document.myForm.myText.value;”>Copy Text Field</a>


46 偵測文字框的變化

1: <form name=”myForm”>
2: Enter some Text: <input type=”text” name=”myText” onChange=”alert(this.value);”>
3: </form>


47 訪問選中的Select

1: <form name=”myForm”>
2: <select name=”mySelect”>
3: <option value=”First Choice”>1</option>
4: <option value=”Second Choice”>2</option>
5: <option value=”Third Choice”>3</option>
6: </select>
7: </form>
8: <a href='#' onClick='alert(document.myForm.mySelect.value);'>Check Selection List</a>


48 動態增加Select項

1: <form name=”myForm”>
2: <select name=”mySelect”>
3: <option value=”First Choice”>1</option>
4: <option value=”Second Choice”>2</option>
5: </select>
6: </form>
7: <script language=”JavaScript”>
8: document.myForm.mySelect.length++;
9: document.myForm.mySelect.options[document.myForm.mySelect.length - 1].text = “3”;
10: document.myForm.mySelect.options[document.myForm.mySelect.length - 1].value = “Third Choice”;
11: </script>


49 驗證表單欄位

1: <script language=”JavaScript”>
2: function checkField(field) {
3: if (field.value == “”) {
4: window.alert(“You must enter a value in the field”);
5: field.focus();
6: }
7: }
8: </script>
9: <form name=”myForm” action=”target.html”>
10: Text Field: <input type=”text” name=”myField”onBlur=”checkField(this)”>
11: <br/><input type=”submit”>
12: </form>


50 驗證Select項

1: function checkList(selection) {
2: if (selection.length == 0) {
3: window.alert(“You must make a selection from the list.”);
4: return false;
5: }
6: return true;
7: }

51 動態改變表單的action

1: <form name=”myForm” action=”login.html”>
2: Username: <input type=”text” name=”username”><br/>
3: Password: <input type=”password” name=”password”><br/>
4: <input type=”button” value=”Login” onClick=”this.form.submit();”>
5: <input type=”button” value=”Register” onClick=”this.form.action = ‘register.html’; this.form.submit();”>
6: <input type=”button” value=”Retrieve Password” onClick=”this.form.action = ‘password.html’; this.form.submit();”>
7: </form>


52 使用影象按鈕

1: <form name=”myForm” action=”login.html”>
2: Username: <input type=”text” name=”username”><br/>
3: Password: <input type=”password”name=”password”><br/>
4: <input type=”image” src="/”login.gif"” value=”Login”>
5: </form>
6:


53 表單資料的加密

1: <SCRIPT LANGUAGE='JavaScript'>
2: <!--
3: function encrypt(item) {
4: var newItem = '';
5: for (i=0; i < item.length; i++) {
6: newItem += item.charCodeAt(i) + '.';
7: }
8: return newItem;
9: }
10: function encryptForm(myForm) {
11: for (i=0; i < myForm.elements.length; i++) {
12: myForm.elements[i].value = encrypt(myForm.elements[i].value);
13: }
14: }
15:
16: //-->
17: </SCRIPT>
18: <form name='myForm' onSubmit='encryptForm(this); window.alert(this.myField.value);'>
19: Enter Some Text: <input type=text name=myField><input type=submit>
20: </form>

 


JavaScript就這麼回事5:視窗和框架


54 改變瀏覽器狀態列文字提示

1: <script language=”JavaScript”>
2: window.status = “A new status message”;
3: </script>


55 彈出確認提示框

1: <script language=”JavaScript”>
2: var userChoice = window.confirm(“Click OK or Cancel”);
3: if (userChoice) {
4: document.write(“You chose OK”);
5: } else {
6: document.write(“You chose Cancel”);
7: }
8: </script>


56 提示輸入

1: <script language=”JavaScript”>
2: var userName = window.prompt(“Please Enter Your Name”,”Enter Your Name Here”);
3: document.write(“Your Name is “ + userName);
4: </script>


57 開啟一個新視窗

1: //開啟一個名稱為myNewWindow的瀏覽器新視窗
2: <script language=”JavaScript”>
3: window.open(“http://www.liu21st.com/”,”myNewWindow”);
4: </script>


58 設定新視窗的大小

1: <script language=”JavaScript”>
2: window.open(“http://www.liu21st.com/”,”myNewWindow”,'height=300,width=300');
3: </script>


59 設定新視窗的位置

1: <script language=”JavaScript”>
2: window.open(“http://www.liu21st.com/”,”myNewWindow”,'height=300,width=300,left=200,screenX=200,top=100,screenY=100');
3: </script>


60 是否顯示工具欄和滾動欄

1: <script language=”JavaScript”>
2: window.open(“http:


61 是否可以縮放新視窗的大小

1: <script language=”JavaScript”>
2: window.open('http://www.liu21st.com/' , 'myNewWindow', 'resizable=yes' );</script>


62 載入一個新的文件到當前視窗

1: <a href='#' onClick='document.location = '125a.html';' >Open New Document</a>


63 設定頁面的滾動位置

1: <script language=”JavaScript”>
2: if (document.all) { //如果是IE瀏覽器則使用scrollTop屬性
3: document.body.scrollTop = 200;
4: } else { //如果是NetScape瀏覽器則使用pageYOffset屬性
5: window.pageYOffset = 200;
6: }</script>


64 在IE中開啟全屏視窗

1: <a href='#' onClick=”window.open('http://www.juxta.com/','newWindow','fullScreen=yes');”>Open a full-screen window</a>


65 新視窗和父視窗的操作

1: <script language=”JavaScript”>
2: //定義新視窗
3: var newWindow = window.open(“128a.html”,”newWindow”);
4: newWindow.close(); //在父視窗中關閉開啟的新視窗
5: </script>
6: 在新視窗中關閉父視窗
7: window.opener.close()


66 往新視窗中寫內容

1: <script language=”JavaScript”>
2: var newWindow = window.open(“”,”newWindow”);
3: newWindow.document.open();
4: newWindow.document.write(“This is a new window”);
5: newWIndow.document.close();
6: </script>


67 載入頁面到框架頁面

1: <frameset cols=”50%,*”>
2: <frame name=”frame1” src="/”135a.html"”>
3: <frame name=”frame2” src="/”about:blank"”>
4: </frameset>
5: 在frame1中載入frame2中的頁面
6: parent.frame2.document.location = “135b.html”;


68 在框架頁面之間共享指令碼
如果在frame1中html檔案中有個指令碼

1: function doAlert() {
2: window.alert(“Frame 1 is loaded”);
3: }

那麼在frame2中可以如此呼叫該方法

1: <body onLoad=”parent.frame1.doAlert();”>
2: This is frame 2.
3: </body>


69 資料公用
可以在框架頁面定義資料項,使得該資料可以被多個框架中的頁面公用

1: <script language=”JavaScript”>
2: var persistentVariable = “This is a persistent value”;
3: </script>
4: <frameset cols=”50%,*”>
5: <frame name=”frame1” src="/”138a.html"”>
6: <frame name=”frame2” src="/”138b.html"”>
7: </frameset>


這樣在frame1和frame2中都可以使用變數persistentVariable
70 框架程式碼庫
根據以上的一些思路,我們可以使用一個隱藏的框架頁面來作為整個框架集的程式碼庫

1: <frameset cols=”0,50%,*”>
2: <frame name=”codeFrame” src="/”140code.html"”>
3: <frame name=”frame1” src="/”140a.html"”>
4: <frame name=”frame2” src="/”140b.html"”>
5: </frameset>
 

相關文章