function square(num) {
var total = num * num; // 局部變量
return total;
}
var total = 50; // 全局變量
var number = square(20);
console.log(total); // 50 → 全局 total 未被修改
// 若函數內省略 var
function square2(num) {
total = num * num; // 隱式全局變量!嚴格模式下拋錯
return total;
}
var total = 50;
square2(20);
console.log(total); // 400 → 全局 total 被修改
結論:永遠聲明變量(var/let/const),嚴格模式(`'use strict'`)可攔截隱式全局變量。
if (true) {
var a = 1; // 函數/全局作用域
let b = 2; // 塊級作用域
const c = 3; // 塊級常量
}
console.log(a); // 1
console.log(b); // ReferenceError
console.log(c); // ReferenceError
body {
color: white;
background-color: black;
}
/*
color 可繼承 → 所有後代元素字體變白
background-color 不可繼承 → 僅 body 有黑背景,子元素透明
*/
/* id 選擇器權重:0,1,0,0;類選擇器 0,0,1,0;標籤 0,0,0,1 */
#purchases { color: red; } /* 高優先級 */
| 方法 | 返回 | 範圍 | 備註 |
|---|---|---|---|
getElementById(id) | Element / null | 全文檔 | ID 唯一,最快 |
getElementsByTagName(tag) | HTMLCollection (即時) | 全文檔/元素 | 即使只有一個也返回集合 |
getElementsByClassName(class) | HTMLCollection (即時) | 全文檔/元素 | IE9+ |
querySelector(selector) | Element / null | 全文檔/元素 | 支援完整 CSS 選擇器,**首選** |
querySelectorAll(selector) | NodeList (靜態) | 全文檔/元素 | 非即時,支援 forEach |
// 獲取所有 li
const items = document.getElementsByTagName('li');
for (let i = 0; i < items.length; i++) {
console.log(typeof items[i]); // "object" (HTMLLIElement)
}
// 現代寫法
document.querySelectorAll('li').forEach(li => console.log(li));
const link = document.getElementById('mylink');
// 獲取
const href = link.getAttribute('href'); // 返回 HTML 屬性原始值
// 設置
link.setAttribute('title', '提示文字');
link.setAttribute('data-id', '123'); // data-* 屬性
// 注意:getAttribute 不屬於 document,屬於 Element
// boolean 屬性(disabled, checked, selected)
link.getAttribute('disabled'); // 返回 "" (空字串) 或 null
link.hasAttribute('disabled'); // true/false,更語義化
| 場景 | 用 Property | 用 Attribute |
|---|---|---|
| 表單值 | `input.value`、`input.checked`、`select.selectedIndex` | ❌ |
| 樣式 | `el.style.color`、`el.classList` | ❌ |
| 自定義數據 | `el.dataset.xxx` | `get/setAttribute('data-xxx')` |
| href/src 絕對路徑 | `link.href`(解析後絕對 URL) | `link.getAttribute('href')`(原始值) |
| boolean 屬性 | `input.disabled = true` | `setAttribute('disabled', '')` |
const shopping = document.getElementById('purchases');
// 設置 title 屬性(懸浮提示)
shopping.setAttribute('title', '商品清單');
// 讀取 data-* 數據
const userId = shopping.dataset.userId; // 對應 data-user-id
// 切換禁用狀態
shopping.disabled = true; // Property 方式
// shopping.setAttribute('disabled', ''); // Attribute 方式
// 類名操作(現代)
shopping.classList.add('highlight');
shopping.classList.remove('hidden');
shopping.classList.toggle('active');
掌握「作用域 → 選取 → 屬性操作」三位一體,是原生 JS 開發的基石。現代開發優先使用 `let/const`、`querySelectorAll`、`classList`、`dataset`、Property 訪問,僅在需操作原始 HTML 屬性值(如未解析的 href、boolean 屬性無對應 property)時使用 `get/setAttribute`。