jQuery 的核心價值在於:**統一的 DOM 選取器、鏈式調用、隱式迭代、跨瀏覽器事件模型、豐富的 DOM 操作工具函數**。本文將核心 API 系統歸類,作為開發時的速查手冊 (基於 jQuery 3.x)。
// 建立
$() / jQuery() // 空集合
$(selector, context) // 核心選取
$(htmlString) // 建立新元素
$(element) / $(elementArray) // 包裝原生 DOM
$(callback) // 綁定 DOMContentLoaded (等同 $(document).ready())
// jQuery 物件 → 原生
$('#id')[0] // 取第一個 DOM
$('#id').get(0) // 同上
$('#id').get() // 取全部 DOM 陣列
$('#id').toArray() // 同 get()
// 原生 → jQuery
$(nativeElement)
$(nativeArray)
| 類別 | 範例 | 說明 |
|---|---|---|
| 基本 | #id, .class, tag, *, sel1, sel2 | ID、類別、標籤、通配、群組 |
| 層級 | ancestor descendant, parent > child, prev + next, prev ~ siblings | 後代、直接子代、相鄰兄弟、一般兄弟 |
| 屬性 | [attr], [attr=val], [attr!=val], [attr^=val], [attr$=val], [attr*=val] | 存在、等於、不等、開頭、結尾、包含 |
| 基本過濾 | :first, :last, :eq(n), :even, :odd, :gt(n), :lt(n), :not(selector) | 位置、否定 |
| 內容過濾 | :contains(text), :empty, :has(selector), :parent | 文本、空、包含子元素、有子元素 |
| 可見性 | :visible, :hidden | 實際可見/隱藏 (含 display:none, type=hidden) |
| 表單 | :input, :text, :password, :checkbox, :selected, :checked, :enabled, :disabled | 表單元素狀態 |
| 子元素 | :first-child, :last-child, :nth-child(n), :only-child | 父元素下的位置 |
| 方向 | 方法 | 說明 |
|---|---|---|
| 向上 (祖先) | .parent([sel]) | 直接父元素 (可選擇器過濾) |
.parents([sel]) | 所有祖先 (至 document) | |
.closest(sel) | **最近**匹配選擇器的祖先 (含自己),事件委派常用 | |
| 向下 (後代) | .children([sel]) | 直接子元素 (不含文本節點) |
.find(sel) | 所有後代 (最常用,**必須提供選擇器**) | |
.contents() | 所有子節點 (含文本、註釋),iframe 可穿透 | |
| 同級 | .siblings([sel]) | 所有兄弟 (不含自己) |
.next([sel]) / .prev([sel]) | 下一個/上一個兄弟 | |
| .nextAll() / .prevAll() | 所有後續/前序兄弟 | |
| .nextUntil(sel) / .prevUntil(sel) | 直到匹配選擇器為止 |
// 過濾
$('li').filter('.active') // 符合選擇器
$('li').filter(function(i){ return $(this).text().length > 10; }) // 函數過濾
$('li').not('.active') // 排除
$('li').not(function(){ return $(this).hasClass('hide'); })
$('li').slice(0, 3) // 索引範圍 [0,3) → 前3個
$('li').first() / .last() // 首/尾
$('li').eq(2) // 指定索引 (負數倒數)
$('li').map(function(i){ return this.id; }).get() // 轉陣列
// HTML 屬性 (Attribute)
.attr('href') / .attr('href', 'url') // 獲取/設置屬性
.removeAttr('disabled')
.prop('checked') / .prop('checked', true) // **DOM Property (推薦用於布林/動態屬性)**
.removeProp('customProp')
// 資料屬性
.data('key') / .data('key', val) // 內部緩存 (支援物件)
.data() // 取得全部
.removeData('key')
// HTML5 data-*
.attr('data-id') / .attr('data-id', 123) // 操作屬性節點
// 或
el.dataset.id (原生,僅字串)
鐵律: **布林屬性 (checked, disabled, selected, readonly) 必用 .prop()**;自定義屬性/ARIA 用 .attr();內部緩存用 .data()。
.html() / .html('<b>bold</b>') // innerHTML
.text() / .text('text <b>bold</b>') // textContent (自動轉義)
.val() / .val(['opt1', 'opt2']) // 表單值 (多選陣列)
// 內部插入
.append(content) / .prepend(content)
.appendTo(target) / .prependTo(target)
// 外部插入
.after(content) / .before(content)
.insertAfter(target) / .insertBefore(target)
// 包裹
.wrap('<div class="wrapper"></div>')
.wrapAll('<div></div>') // 整組包裹
.wrapInner('<span></span>') // 內容包裹
.unwrap() // 移除父層
// 替換/移除/清空
.replaceWith(newContent)
.replaceAll(target)
.remove([selector]) // 移除自己 (可選擇器過濾)
.detach() // 移除但保留 data/events (重新插入可用)
.empty() // 清空子節點
// 複製
.clone(true) // true: 複製事件/資料
.css('color') / .css({color:'red', 'font-size':'14px'})
.addClass('c1 c2') / .removeClass('c1') / .toggleClass('c1') / .hasClass('c1')
// 尺寸 (無單位像素值)
.width() / .height() // content box
.innerWidth() / .innerHeight() // + padding
.outerWidth() / .outerHeight() // + border
.outerWidth(true) / .outerHeight(true) // + margin
// 位置
.offset() // 相對文檔 {top, left}
.position() // 相對 offsetParent {top, left}
.offsetParent() // 最近的定位祖先
.scrollTop() / .scrollLeft() // 獲取/設置捲動位置
// 直接綁定
$(sel).on('click', handler)
$(sel).on('click', {foo: 'bar'}, handler) // e.data.foo
// 委派綁定 (動態元素)
$(parent).on('click', 'child-sel', handler)
// 多事件、命名空間
$(sel).on('click.myNS focus.myNS', handler)
$(sel).off('click.myNS') // 精準解綁
// 一次性
$(sel).one('click', handler)
// 觸發
$(sel).trigger('click')
$(sel).trigger('customEvent', [arg1, arg2]) // 額外參數傳給 handler(e, arg1, arg2)
$(sel).triggerHandler('click') // 不冒泡、不觸發預設行為、返回 handler 返回值
| 屬性/方法 | 說明 |
|---|---|
e.target | 觸發事件的原始元素 |
e.currentTarget | 綁定監聽器的元素 (等同 this) |
e.delegateTarget | 委派綁定的祖先元素 |
e.which | 鍵碼/滑鼠鍵統一 (鍵盤: keyCode/charCode; 滑鼠: 1左 2中 3右) |
e.pageX / e.pageY | 相對文檔座標 (已修正捲動) |
e.preventDefault() | 阻止預設行為 |
e.stopPropagation() | 阻止冒泡 |
e.stopImmediatePropagation() | 阻止冒泡 + 同元素其他監聽器 |
e.data | 綁定時傳遞的額外數據 |
// 基礎顯示/隱藏
.show(400) / .hide(400) / .toggle(400)
.fadeIn/Out/Toggle(400)
.slideDown/Up/Toggle(400)
// 自訂動畫
.animate({opacity: 0.5, width: '200px'}, 400, 'swing', function(){})
// easing: 'swing' (預設) / 'linear' / jQuery UI/easing 插件擴展
// 隊列控制
.delay(1000) // 延遲
.stop(true, true) // 清空隊列、跳至結束
.finish() // 當前+隊列全部跳至結束
.queue('fx', function(next){ ... next(); }) // 自訂隊列
.dequeue('fx')
$.ajax({
url: '/api/users',
method: 'POST',
data: { name: 'John' }, // 物件自動序列化為 application/x-www-form-urlencoded
dataType: 'json', // 預期回應類型 (自動解析)
headers: { 'X-CSRF-Token': '...' },
timeout: 5000,
beforeSend: function(xhr){ xhr.setRequestHeader('Authorization', 'Bearer ...'); },
success: function(data, textStatus, jqXHR){},
error: function(jqXHR, textStatus, errorThrown){},
complete: function(jqXHR, textStatus){}
});
// 簡寫
$.get(url, data, success, dataType)
$.post(url, data, success, dataType)
$.getJSON(url, data, success)
$.getScript(url, success)
// 全域事件 (ajaxStart, ajaxStop, ajaxError, ajaxSuccess, ajaxComplete, ajaxSend)
$(document).ajaxStart(function(){ $('#loading').show(); });
$(document).ajaxStop(function(){ $('#loading').hide(); });
$.extend(true, target, obj1, obj2) // 深拷貝合併
$.each(obj, function(key, val){}) // 陣列/物件迭代
$.map(arr, function(val, i){ return val*2; }) // 映射返回新陣列
$.grep(arr, function(val, i){ return val > 10; }) // 過濾返回新陣列
$.type(null) // 'null'; $.type([]) // 'array'; $.type(/re/) // 'regexp'
$.now() // Date.now()
$.proxy(fn, context) // 綁定 this (ES6 箭頭函數可替代)
$.makeArray(obj) // 類陣列轉真陣列
$.inArray(val, arr) // 索引 (ES6: arr.indexOf(val))
$.uniqueSort(arr) // 去重排序 (DOM 元素陣列專用)
.load() (事件)、.unload(), .error() → 用 .on()。.andSelf() → .addBack()。.data() 不再轉換屬性值 (如 data-foo="true" 返回字串 "true" 而非 Boolean)。.width()/.height() 返回精確浮點數 (含 transform 縮放)。Promise/A+,.then() 異步微任務。jQuery API 設計極度內聚:選取 → 遍歷 → 操作 → 事件 → 效果 → Ajax → 工具,形成閉環。掌握上述分類速查,能讓你在維護舊專案、閱讀舊代碼、或需快速原型開發時游刃有餘。新專案請拥抱原生標準與現代框架,但理解 jQuery 核心模式,將助你更深刻理解前端工程演進邏輯。