萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 變量作用域、DOM 屬性操作與元素選取完整指南

第一部分:變量作用域與提升

1. var 的函數作用域與提升

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'`)可攔截隱式全局變量。

2. let/const 塊級作用域(ES6+)

if (true) {
  var a = 1;   // 函數/全局作用域
  let b = 2;   // 塊級作用域
  const c = 3; // 塊級常量
}
console.log(a); // 1
console.log(b); // ReferenceError
console.log(c); // ReferenceError

第二部分:CSS 繼承與層疊

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; } /* 高優先級 */

第三部分:DOM 元素選取 API

方法返回範圍備註
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));

第四部分:元素屬性操作

1. getAttribute / setAttribute(標準屬性)

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,更語義化

2. DOM Property(屬性對象) vs HTML Attribute

場景用 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', '')`

3. 實戰示例

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');

第五部分:常見陷阱

  • 即時集合陷阱:`getElementsByTagName` 返回即時集合,循環中刪除元素會導致索引偏移 → 先轉陣列 `Array.from(list)` 或反向循環。
  • 屬性值類型:`getAttribute` 永遠返回字串或 null;`el.value` 返回字串;`el.checked` 返回布爾值。
  • 自定義屬性:務必用 `data-*` 前綴,配合 `dataset` 讀寫,避免污染標準屬性命名空間。

結語

掌握「作用域 → 選取 → 屬性操作」三位一體,是原生 JS 開發的基石。現代開發優先使用 `let/const`、`querySelectorAll`、`classList`、`dataset`、Property 訪問,僅在需操作原始 HTML 屬性值(如未解析的 href、boolean 屬性無對應 property)時使用 `get/setAttribute`。

copyright © 萬盛學電腦網 all rights reserved