以下依主題整理前端開發常見的 JavaScript 語句,方便隨手翻查。
document.write(" "); // 輸出
// 註解
var 變數; // 宣告變數
if (condition) {} else {} // 條件判斷
for ([初始]; [條件]; [更新]) {} // 迴圈
break; // 中止迴圈
function functionName([參數], ...) { 敘述 } // 定義函式
值型別:String、Number、Boolean、Null、Object、Function。
比較運算子:== 相等、!= 不相等、>、>=、<、<=。
型別轉換:
parseInt(str, 10); // 字串 → 整數 parseFloat(str); // 字串 → 浮點數 "" + 變數; // 數值 → 字串 isNaN(變數); // 是否為非數值
document.getElementById("id"); // 取得元素
document.getElementsByTagName("div"); // 依標籤取得
document.createElement("div"); // 建立元素
document.createTextNode("文字"); // 建立文字節點
document.forms[0]; // 第一個表單
document.forms.length; // 表單數量
document.close(); // 關閉輸出流
element.name / element.value // 表單元素的名稱與值
HTML 文件順序:document → html → (head, body)。
視窗 DOM 順序:window → (navigator, screen, history, location, document)。
// 清空表單中所有文字欄位
var form = window.document.forms[0];
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].type == "text") {
form.elements[i].value = "";
}
}
window.open(url); // 開啟視窗
window.close(); // 關閉視窗
self; // 視窗本身
window.status = "字串"; // 狀態列文字
window.defaultStatus = "字串";
window.alert("字串"); // 提示訊息
window.confirm("字串"); // 確認框,回傳布林
window.prompt("訊息", "預設值"); // 輸入框
window.location.href = "URL"; // 指定目前顯示位置
window.navigate("URL"); // 導向(舊)
window.print(); // 列印
window.scroll(x, y); // 捲動到絕對位置
window.scrollBy(x, y); // 相對捲動
setInterval("expr", msec); // 定時重複執行
setTimeout(fn, msec); // 延遲執行一次
location 的屬性:protocol(http:)、hostname(www.example.com)、port(80)、host(www.example.com:80)、pathname(/a/a.html)、hash(#anchor)、href(完整資訊)。
window.location.reload(); // 重新整理 window.history.back(); // 上一頁 window.history.forward(); // 下一頁 window.history.go(-1); // 相對頁數 top; // 框架集最頂層 parent; // 父視窗 opener; // 開啟子視窗的父視窗
document.forms[0].checkThis.checked // 核取方塊是否勾選 document.forms[0].groupName.length // 單選鈕組長度 document.forms[0].sel.options[n].value // 下拉選單的值 document.forms[0].sel.selectedIndex // 選中項索引 element.focus(); // 取得焦點 element.blur(); // 失去焦點 element.select(); // 選中內容 element.disabled = true; // 設為禁用 element.isDisabled // 是否禁用 element.tabIndex = 1; // 焦點順序
var myString = new String("This is lightsword");
myString.length // 長度
string.toUpperCase(); // 轉大寫
string.toLowerCase(); // 轉小寫
String1.indexOf("String2") // 出現位置,-1 代表找不到
string.lastIndexOf(searchString[, startIndex]) // 最後一次出現位置
stringA.charAt(9); // 指定位置的字元
stringA.charCodeAt(9); // 該字元的 ASCII 碼
stringA.substring(2, 6); // 擷取子字串
string.substr(start[, length]); // 擷取指定長度
string.concat(string2); // 串接
string.split("分隔符"); // 切成陣列
string.match(regExp); // 比對
string.replace(regExp, str); // 替換
Math.PI; // 圓周率 Math.SQRT2; // 2 的平方根 Math.max(v1, v2); // 最大值 Math.pow(v1, 10); // 次方 Math.round(v1); // 四捨五入 Math.floor(Math.random() * (n + 1)); // 隨機整數 var today = new Date(); today.getTime(); // 時間戳 today.getFullYear(); // 四位年份 today.getMonth(); // 月份(從 0 起) today.getDate(); // 日 today.getDay(); // 星期幾 today.getHours(); // 時 today.getMinutes(); // 分 today.getSeconds(); // 秒 today.setTime(value); // 設定時間
注意:月份的 get 與 set 都是從 0 開始計。
frames[n].objFuncVarName frames["frameName"].objFuncVarName frameName.objFuncVarName this // 目前所屬物件
內建物件:Array、Boolean、Date、Error、EvalError、Function、Math、Number、Object、RangeError、ReferenceError、RegExp、String、SyntaxError、TypeError、URIError。
換行字元:\n。
常量宣告:const。
<p id="para">how are <em>you</em></p> para.innerHTML; // "how are <em>you</em>"(含標籤) para.innerText; // "how are you"(不含標籤)
contentEditable 可設定元素是否可編輯,isContentEditable 回傳目前狀態。
<script type="text/javascript" src="aaa.js"></script> // 外部 JS <noscript>不支援腳本時顯示的內容</noscript> <!-- //--> // 讓舊瀏覽器略過
在超連結中呼叫 JS:<a href="javascript:myFunc()">。
錯誤處理:window.onerror = handleError; 指定錯誤處理函式。
加入收藏:external.AddFavorite(url, title);(僅舊版 IE 有效)。
這份清單反映的是 2000 年代前後的寫法。其中有幾項今天已經不建議使用:document.write() 會阻斷解析且在某些情境下直接清空文件;showModalDialog() 已被標準 <dialog> 元素取代;element.all、addBehavior()、window.navigate() 都是 IE 專屬且已淘汰;javascript: 偽協定也不應再用於 href。
不過字串、陣列、Math、Date 這些核心 API 至今幾乎沒變,熟記它們的收益依然最高。