有些時候你自認精通一門語言,卻發現自己整天在跟其他語言打交道。這些看似微不足道的東西,往往會在你不知不覺間浪費大量時間。我曾以為自己幾年前就精通 JavaScript,直到現在才越來越覺得它遠比想像中複雜而強大。趁著假日空檔,把 JavaScript 的常用方法和技巧整理成這份大全,希望讓每個為 JS 苦惱的人都能豁然開朗。
建立腳本區塊:
<script language="JavaScript">
JavaScript code goes here
</script>
隱藏腳本碼(在不支援 JS 的瀏覽器中不執行):
<script language="JavaScript">
<!--
document.write("Hello");
// -->
</script>
瀏覽器不支援時的提示:
<noscript>
Hello to the non-JavaScript browser.
</noscript>
連結外部腳本檔:
<script language="JavaScript" src="filename.js"></script>
註解:// 為單行註解,/* ... */ 為多行註解。
輸出到瀏覽器:document.write("<strong>Hello</strong>");
定義變數:var myVariable = "some value";
字串相加:var myString = "String1" + "String2";
字串搜尋與替換:
var therePlace = myVariable.search("there");
thisVar.replace("Monday", "Friday");
建立陣列與排序:
var myArray = new Array(5);
myArray[0] = "First Entry";
// ...
document.write(myArray.sort());
分割字串:
var stringArray = "a,b,c,d".split(",");
彈出警告與確認框:
window.alert("Hello");
var result = window.confirm("Click OK to continue");
定義與呼叫函式:
function multiple(number1, number2) {
var result = number1 * number2;
return result;
}
// 呼叫
<a href="#" onClick="functionName()">Link text</a>
頁面載入完成後執行:<body onLoad="functionName();">
條件判斷:
var result = (userChoice == true) ? "OK" : "Cancel";
指定次數迴圈:
for (i = 0; i < myArray.length; i++) {
document.write(myArray[i] + "<br>");
}
設定未來執行 / 定時執行 / 取消:
window.setTimeout("hello()", 5000);
var myTimeout = window.setTimeout("hello()", 5000);
window.clearTimeout(myTimeout);
存取 document 物件:var myURL = document.URL;
動態輸出 HTML:
document.write("<li>URL: " + document.URL + "</li>");
輸出換行:document.writeln("...");
輸出日期與自訂格式:
var thisDate = new Date();
document.write(thisDate.toString());
var thisTimeString = thisDate.getHours() + ":" + thisDate.getMinutes();
讀取 URL 參數:
var urlParts = document.URL.split("?");
var parameterParts = urlParts[1].split("&");
for (i = 0; i < parameterParts.length; i++) {
var pairParts = parameterParts[i].split("=");
document.write(pairParts[0] + ":" + pairParts[1]);
}
頁面跳轉:window.location = "https://www.example.com/";
讀取圖像屬性:
<a href="#" onClick="window.alert(document.myImage.width)">Width</a>
動態載入圖像:
myImage = new Image;
myImage.src = "image1.jpg";
簡單的圖像替換(滑過換圖):
<a href="#"
onMouseOver="document.myImage.src = rollImage.src;"
onMouseOut="document.myImage.src = defaultImage.src;">
<img src="image1.jpg" name="myImage" width=100 height=100 border=0>
</a>
隨機顯示圖像:
var imageChoice = Math.floor(Math.random() * imageList.length);
document.write('<img src="' + imageList[imageChoice] + '">');
表單構成:
<form method="post" action="target.html" name="thisForm">
<input type="text" name="myText">
<select name="mySelect">
<option value="1">First Choice</option>
</select>
<input type="submit" value="Submit Me">
</form>
存取文字框內容:document.myForm.myText.value
偵測文字框變化:<input onChange="alert(this.value);">
動態增加 Select 選項:
document.myForm.mySelect.length++;
document.myForm.mySelect.options[document.myForm.mySelect.length - 1].text = "3";
驗證表單欄位:
function checkField(field) {
if (field.value == "") {
window.alert("You must enter a value in the field");
field.focus();
}
}
動態改變表單 action:
<input type="button" value="Register"
onClick="this.form.action = 'register.html'; this.form.submit();">
改變狀態列文字:window.status = "A new status message";
提示輸入:
var userName = window.prompt("Please Enter Your Name", "Enter Your Name Here");
開啟新視窗並設定大小與位置:
window.open("https://www.example.com/", "myNewWindow",
'height=300,width=300,left=200,top=100');
新視窗與父視窗互相操作:
var newWindow = window.open("128a.html", "newWindow");
newWindow.close(); // 父視窗關閉新視窗
window.opener.close(); // 新視窗關閉父視窗
框架之間共享資料:可在框架頁面定義一個全域變數,讓多個框架中的頁面共用同一份資料;甚至能用一個隱藏的框架頁面作為整個框架集的程式碼庫。掌握這些基礎技巧,就能在瀏覽器環境中靈活地操作頁面、表單、圖像與視窗了。