基於 jQuery 3.x (現代版本)。jQuery 1.x/2.x 為舊版 (支援 IE6-8),API 大多相容但部分已移除 (如 .live(), .die(), .toggle(fn,fn) 事件切換)。
// 標準寫法 (推薦)
$(function() {
// DOM 就緒執行
});
// 等同於
$(document).ready(function() { ... });
// 嚴格模式下確保 $ 未被覆寫
jQuery(function($) { ... });
// 直接綁定
$('#btn').on('click', handler);
// 事件委派 (動態元素、效能優化)
$('#list').on('click', 'li', handler);
// 多事件
$('#el').on('mouseenter mouseleave', handler);
// 命名空間 (方便解除特定綁定)
$('#el').on('click.myPlugin', handler);
$('#el').off('click.myPlugin'); // 僅移除 myPlugin 命名空間
// 一次性綁定
$('#el').one('click', handler);
// 觸發事件
$('#el').trigger('click');
$('#el').triggerHandler('click'); // 不冒泡、不觸發預設行為
| 類別 | 事件 |
|---|---|
| 滑鼠 | click, dblclick, mousedown, mouseup, mousemove, mouseenter, mouseleave, hover (enter+leave) |
| 鍵盤 | keydown, keyup, keypress (棄用) |
| 表單 | submit, change, focus, blur, focusin, focusout, input, select |
| 視窗 | load, resize, scroll, error, unload, beforeunload |
| 觸控 | touchstart, touchmove, touchend, touchcancel |
| 自訂 | 任意字串,配合 .trigger() |
$('#el').show(duration, easing, callback);
$('#el').hide(duration, easing, callback);
$('#el').toggle(duration, easing, callback);
$('#el').slideDown(400, 'swing');
$('#el').slideUp(400);
$('#el').slideToggle(400);
$('#el').fadeIn(400);
$('#el').fadeOut(400);
$('#el').fadeToggle(400);
$('#el').fadeTo(400, 0.5); // 淡入至指定透明度
$('#el').animate({
opacity: 0.5,
width: '300px',
marginLeft: '+=50' // 相對值
}, {
duration: 1000,
easing: 'swing', // 或 'linear',或引入 jQuery UI/easing plugin
complete: function() { console.log('動畫結束'); },
step: function(now, fx) { /* 每幀回調 */ },
queue: true // 是否進入動畫隊列
});
// 停止動畫
$('#el').stop(true, true); // 清除隊列、跳至終點
$('#el').finish(); // 完成所有排隊動畫
// Attribute (HTML 屬性)
$('#el').attr('href', '/new'); // 設定
$('#el').attr('href'); // 取得
$('#el').removeAttr('disabled'); // 移除
// Property (DOM 屬性) - 推薦用於布林屬性
$('#el').prop('disabled', true); // 停用
$('#el').prop('checked', true); // 勾選
$('#el').prop('selectedIndex', 2); // select 選中索引
// Data-* (HTML5 資料屬性)
$('#el').data('userId', 123); // 設定 (記憶體,不寫入 DOM)
$('#el').data('userId'); // 取得
$('#el').attr('data-user-id'); // 讀寫實際 HTML 屬性
$('#el').css('color', 'red'); // 單一
$('#el').css({ color: 'red', fontSize: '14px' }); // 多個 (駝峰命名)
$('#el').addClass('active');
$('#el').removeClass('hidden');
$('#el').toggleClass('highlight');
$('#el').hasClass('active'); // Boolean
// 內容
$('#el').html('新內容'); // HTML
$('#el').text('純文字'); // 文字 (自動跳脫)
$('#el').val('新值'); // 表單值
// 插入 (內部)
$('#parent').append('新項目 '); // 末尾
$('#parent').prepend('首項 '); // 開頭
$('項目 ').appendTo('#parent'); // 反向
// 插入 (外部)
$('#target').after('之後');
$('#target').before('之前');
$('包裹').insertAfter('#target');
// 包裹
$('#el').wrap('');
$('#el').wrapInner('');
$('#el').unwrap(); // 移除父層
// 替換/移除
$('#el').replaceWith('新元素');
$('#el').remove(); // 移除自身 (含事件/資料)
$('#el').detach(); // 移除但保留事件/資料 (可重新插入)
$('#el').empty(); // 清空子元素
// 向上
$('#el').parent(); // 父元素
$('#el').parents('.wrapper'); // 所有祖先 (可選擇器過濾)
$('#el').closest('.modal'); // 最近祖先 (含自己),常用於委派事件找容器
// 向下
$('#el').children(); // 直接子元素
$('#el').find('.item'); // 所有後代 (最常用)
$('#el').contents(); // 所有子節點 (含文字節點、iframe 文檔)
// 同層
$('#el').siblings(); // 所有兄弟
$('#el').next(); // 下一個兄弟
$('#el').prev(); // 上一個兄弟
$('#el').nextAll(); // 之後所有
$('#el').prevAll(); // 之前所有
// 篩選
$('li').first(); // 第一個
$('li').last(); // 最後
$('li').eq(2); // 索引 2 (第 3 個)
$('li').filter('.active'); // 符合選擇器
$('li').not('.hidden'); // 不符合
$('li').slice(1, 4); // 索引 1-3
// 迭代
$('li').each(function(i, el) {
// this === el (原生 DOM)
// $(this) === jQuery 物件
});
$.ajax({
url: '/api/users',
method: 'POST', // type 別名
data: { name: 'John' }, // 物件自動序列化為 query string
dataType: 'json', // 預期回應類型:json, xml, html, script, text, jsonp
contentType: 'application/x-www-form-urlencoded; charset=UTF-8', // 發送類型
headers: { 'X-CSRF-Token': token }, // 自訂標頭
timeout: 10000, // 逾時毫秒
cache: false, // GET 請求加時間戳防快取
xhrFields: { withCredentials: true }, // 跨域攜帶 Cookie
beforeSend: function(xhr) { /* 請求前 */ },
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); // 自動 dataType: 'json'
$.getScript(url, success); // 載入並執行 JS
$(document).ajaxStart(function() { $('#loading').show(); });
$(document).ajaxStop(function() { $('#loading').hide(); });
$(document).ajaxError(function(e, jqXHR, settings, err) { logError(err); });
$('#form').serialize(); // "name=John&age=30"
$('#form').serializeArray(); // [{name:'name',value:'John'}, ...]
// 手動轉物件
var obj = {};
$('#form').serializeArray().forEach(f => obj[f.name] = f.value);
// 類型檢查
$.type(null); // "null"
$.isArray([]); // true
$.isPlainObject({}); // true (純物件 {})
$.isFunction(fn); // true
$.isNumeric('123'); // true
$.isWindow(window); // true
// 字串
$.trim(' abc '); // "abc"
// 陣列/物件操作
$.each([1,2], function(i, v) { ... }); // 陣列/物件通用迭代
$.extend(true, {}, obj1, obj2); // 深度合併 (true=deep)
$.merge(arr1, arr2); // 合併陣列 (修改 arr1)
$.grep(arr, function(v) { return v > 2; }); // 過濾
$.map(arr, function(v) { return v * 2; }); // 映射
$.inArray(val, arr); // 索引 (-1 不存在)
$.uniqueSort(arr); // 去重排序 (DOM 元素專用)
// 解析
$.parseJSON('{"a":1}'); // 同 JSON.parse (jQuery 3.0+ 棄用)
$.parseXML(xmlStr); // XML 文檔
// 其他
$.noop(); // 空函數
$.now(); // Date.now()
$.proxy(fn, context); // 綁定 this (ES6 箭頭函數替代)
$.support; // 特性偵測物件
$('#el')
.addClass('active')
.css('color', 'red')
.on('click', handler)
.find('.child')
.text('子元素')
.end() // 回到上一層 #el
.fadeOut();
// this 在回調中
$('li').each(function() {
this; // 原生 DOM 元素
$(this); // jQuery 包裝
});
| 陷阱 | 正確做法 |
|---|---|
.live(), .delegate() | 用 .on() 事件委派 |
.toggle(fn, fn) (事件切換) | 用布林旗標或 .one() 重新綁定 |
attr('checked') 取勾選狀態 | prop('checked') 或 is(':checked') |
$.browser | 特徵偵測 $.support 或 Modernizr |
| 大量 DOM 操作不離線 | 用 DocumentFragment、detach()、字串拼接後 .html() |
| 選擇器效能 | ID > class > 標籤 > 通用;避免過度嵌套;快取 jQuery 物件 |
jQuery 仍是大量存量專案的基石。掌握 .on() 事件委派、.prop() vs .attr()、.animate() 隊列、.ajax() 完整配置、遍歷鏈 (.find()/.closest()/.end()) 是維護與重構的關鍵。新專案建議漸進式遷移至原生 API (Fetch, classList, addEventListener) 或現代框架 (Vue/React/Svelte)。