本文整理 JavaScript 開發中最高頻的 10 類核心操作,涵蓋 DOM 寫入、事件綁定、內容修改、圖片切換、樣式控制、大小寫敏感、變數宣告習慣、undefined 特性、物件建立、表單驗證,每項皆附完整可執行程式碼,適合新手速查與老手複習。
document.write() 僅適用於頁面載入階段,載入後呼叫會覆蓋整個文檔。
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph</p>");
最直觀但不推薦大型專案使用(結構與行為耦合),現代開發建議用 addEventListener。
<button type="button" onclick="alert('Welcome!')">點擊這裡</button>
核心 API:element.innerHTML,可插入 HTML 標籤;若僅需純文字請用 textContent 避免 XSS。
var x = document.getElementById("demo");
x.innerHTML = "Hello JavaScript";
修改 img.src 即可,建議預載圖片避免閃爍。
var img = document.getElementById('myimage');
img.src = "../i/eg_bulboff.gif";
使用 element.style.cssProperty,CSS 屬性名需轉駝峰命名(如 backgroundColor)。
var x = document.getElementById("demo");
x.style.color = "#ff0000";
getElementById ≠ getElementbyIDmyVariable ≠ MyVariable雖然 ES6 有 let/const 塊級作用域,但在函式頂部集中宣告仍有助於閱讀與除錯。
var carname; // 值為 undefined
console.log(carname === undefined); // true
var person = new Object();
person.firstname = "Bill";
person.lastname = "Gates";
person.age = 56;
person.eyecolor = "blue";
const person = {
firstname: "Bill",
lastname: "Gates",
age: 56,
eyecolor: "blue",
fullName() { return this.firstname + " " + this.lastname; }
};
經典表單提交前驗證模式,回傳 false 可阻止表單送出。
<form action="submitpage.htm" onsubmit="return validate_form(this)" method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit">
</form>
<script>
function validate_required(field, alertMsg) {
if (field.value == null || field.value === "") {
alert(alertMsg);
field.focus();
return false;
}
return true;
}
function validate_form(form) {
return validate_required(form.email, "Email must be filled out!");
}
</script>
現代專案優先使用 HTML5 屬性,減少 JS 邏輯:
<form>
<input type="email" name="email" required placeholder="請輸入 Email">
<input type="submit">
</form>
瀏覽器會自動攔截空值與格式錯誤,無需撰寫 JS 驗證碼。