| 層次 | 掛載位置 | 調用方式 | 適用場景 |
|---|---|---|---|
| 全局函數 | jQuery.fn / jQuery | $.myFunc() | 工具函數、命名空間、無 DOM 依賴邏輯 |
| 對象方法 | jQuery.fn (即 jQuery.prototype) | $("selector").myMethod() | 操作 DOM 元素、鏈式調用、隱式迭代 |
| 選擇器擴展 | jQuery.expr[":"] | $("div:myCustom") | 自定義選擇器邏輯 |
jQuery.myUtil = function() { alert("工具函數"); };
$.myUtil(); // 調用
jQuery.utilA = function() { ... };
jQuery.utilB = function() { ... };
$.utilA(); $.utilB();
jQuery.myPlugin = {
version: "1.0.0",
author: "Team",
// 工具函數
formatDate: function(date, fmt) { ... },
// 配置管理
config: { debug: false },
// 內部方法(慣例下劃線前綴)
_internalHelper: function() { ... },
// 初始化入口
init: function(options) {
this.config = $.extend(this.config, options);
}
};
// 使用
$.myPlugin.init({ debug: true });
$.myPlugin.formatDate(new Date(), "yyyy-MM-dd");
jQuery.fn.myPlugin = function(options) {
// this 指向 jQuery 對象(包含 0~N 個 DOM 元素)
return this.each(function() {
// this 指向單個 DOM 元素
var $el = $(this);
// 插件邏輯...
});
};
永遠在方法內部使用 this.each() 遍歷匹配元素集合,確保插件行為與 jQuery 內置方法一致(如 css(), hide())。
// ❌ 錯誤:直接操作 this(jQuery 對象),僅影響第一個元素或行為異常
jQuery.fn.badSwap = function(class1, class2) {
if (this.hasClass(class1)) this.removeClass(class1).addClass(class2);
// 多個元素時,this.hasClass 只檢查第一個,addClass 應用於所有,邏輯錯亂
};
// ✅ 正確:隱式迭代
jQuery.fn.goodSwap = function(class1, class2) {
return this.each(function() {
var $el = $(this);
if ($el.hasClass(class1)) $el.removeClass(class1).addClass(class2);
else if ($el.hasClass(class2)) $el.removeClass(class2).addClass(class1);
});
};
jQuery.fn.chainable = function() {
return this.each(function() {
// 處理邏輯
});
};
// 支持鏈式:$("div").chainable().css("color", "red").fadeIn();
jQuery.fn.shadow = function(opts) {
return this.each(function() {
var $el = $(this);
for (var i = 0; i < opts.slices; i++) {
$el.clone().css({
position: "absolute",
left: $el.offset().left + i,
top: $el.offset().top + i,
zIndex: opts.zIndex,
opacity: opts.opacity
}).appendTo("body");
}
});
};
// 調用:$("h1").shadow({ slices: 5, opacity: 0.25, zIndex: -1 });
jQuery.fn.shadow = function(options) {
// 1. 定義默認值
var defaults = {
slices: 5,
opacity: 0.1,
zIndex: -1
};
// 2. 合併:用戶選項覆蓋默認值
// 注意:$.extend(target, source1, source2...) 修改並返回目標對象
var opts = $.extend({}, defaults, options); // {} 為空目標,不汙染 defaults
return this.each(function() {
// 使用 opts.slices, opts.opacity...
});
};
// 調用:$("h1").shadow({ opacity: 0.05 }); // 只覆蓋 opacity,其余用默認值
jQuery.fn.shadow = function(options) {
var defaults = {
slices: 5,
opacity: 0.1,
zIndex: -1,
// 回調函數:計算每層偏移
sliceOffset: function(i) { return { x: i, y: i }; }
};
var opts = $.extend({}, defaults, options);
return this.each(function() {
var $el = $(this);
for (var i = 0; i < opts.slices; i++) {
var offset = opts.sliceOffset(i); // 調用回調
$el.clone().css({
left: $el.offset().left + offset.x,
top: $el.offset().top + offset.y,
zIndex: opts.zIndex,
opacity: opts.opacity
}).appendTo("body");
}
});
};
// 自定義偏移邏輯
$("h1").shadow({
sliceOffset: function(i) { return { x: -i, y: -2*i }; }
});
jQuery.fn.shadow = function(options) {
// 默認值存儲在插件函數屬性上,允許全局修改
var opts = $.extend({}, jQuery.fn.shadow.defaults, options);
// ...
};
// 定義默認值(函數也是對象)
jQuery.fn.shadow.defaults = {
slices: 5,
opacity: 0.1,
zIndex: -1,
sliceOffset: function(i) { return { x: i, y: i }; }
};
// 全局修改默認值(影響後續所有調用)
$.fn.shadow.defaults.opacity = 0.2;
$.fn.shadow.defaults.slices = 3;
// 單次調用覆蓋
$("h1").shadow({ opacity: 0.05 });
(function($, window, document, undefined) {
"use strict";
var pluginName = "myPlugin";
var defaults = {
property: "value",
onInit: null,
onChange: null
};
function Plugin(element, options) {
this.element = element;
this.$element = $(element);
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
$.extend(Plugin.prototype, {
init: function() {
this.setup();
this.bindEvents();
if ($.isFunction(this.settings.onInit)) {
this.settings.onInit.call(this.element);
}
},
setup: function() { /* 初始化 DOM、變量 */ },
bindEvents: function() { /* 綁定事件 */ },
destroy: function() {
this.unbindEvents();
this.$element.removeData(pluginName);
}
});
// 防止重複實例化
$.fn[pluginName] = function(options) {
var args = arguments;
return this.each(function() {
var $this = $(this);
var instance = $this.data(pluginName);
if (!instance) {
// 新建實例
instance = new Plugin(this, typeof options === "object" ? options : {});
$this.data(pluginName, instance);
} else if (typeof options === "string") {
// 調用實例方法:$("div").myPlugin("methodName", arg1, arg2)
if (typeof instance[options] === "function") {
instance[options].apply(this, Array.prototype.slice.call(args, 1));
}
}
});
};
// 暴露默認值允許全局修改
$.fn[pluginName].defaults = defaults;
})(jQuery, window, document);
(function($){ ... })(jQuery); 避免全局汙染、支持無衝突模式$.myPlugin,對象方法掛 $.fn.myPluginreturn this.each(...)return this$.extend({}, defaults, options)$.fn.plugin.defaults = {...}.data(pluginName, instance) 防重複初始化$().plugin("method", args)destroy() 清理事件、數據、DOMjQuery 插件開發的核心在於理解 jQuery.fn 原型機制、掌握 each 隱式迭代與 extend 參數合併模式。從簡單的全局工具函數到功能完整的狀態化插件,遵循「單一職責、鏈式調用、可配置、可銷毀」原則,能編寫出像官方方法一樣優雅、健壯的插件。現代項目雖多用 Vue/React 組件,但 jQuery 插件模式在存量項目維護、輕量級交互、無框架頁面中依然閃光。