編寫 jQuery 插件是復用代碼、構建組件生態的關鍵技能。本文梳理官方推薦規範、核心模式(擴展方法、鏈式調用、默認配置合併)、命名空間隔離,並給出完整開發模板。
jquery.[pluginName].js(如 jquery.color.js)$.fn,工具函數掛載 $(如 $.ajax)this 指向 jQuery 對象(而非原生 DOM),調用 this.each() 遍歷元素return this 保持鏈式;(function($){...})(jQuery),防合併壓縮時語法錯誤$,內部安全使用$.extend({}, defaults, options) 合併用戶選項;(function($) {
// 1. 默認配置
var defaults = {
color: "red",
fontSize: "14px",
onComplete: null
};
// 2. 插件主體
$.fn.myPlugin = function(options) {
// 合併配置
var settings = $.extend({}, defaults, options);
// 遍歷每個匹配元素
return this.each(function() {
var $this = $(this);
// 核心邏輯
$this.css({
color: settings.color,
fontSize: settings.fontSize
});
// 回調
if ($.isFunction(settings.onComplete)) {
settings.onComplete.call(this, $this);
}
});
};
})(jQuery);
;(function($) {
$.fn.extend({
"color": function(value) {
// 設置顏色並返回 this 保持鏈式
return this.css("color", value);
}
});
})(jQuery);
// 使用
$("#div").color("red").css("font-weight", "bold"); // 鏈式調用
需維護實例狀態(如滾動條、燈箱、表單驗證)時,使用 $.widget 或手動數據緑存:
;(function($) {
var pluginName = "scrollSpy";
var defaults = { offset: 100 };
function Plugin(element, options) {
this.element = element;
this.$element = $(element);
this.settings = $.extend({}, defaults, options);
this.init();
}
Plugin.prototype = {
init: function() {
this.bindEvents();
this.checkPosition();
},
bindEvents: function() {
var self = this;
$(window).on("scroll." + pluginName, function() {
self.checkPosition();
});
},
checkPosition: function() {
// 邏輯...
},
destroy: function() {
$(window).off("." + pluginName);
this.$element.removeData(pluginName);
}
};
// 註冊為 jQuery 方法
$.fn[pluginName] = function(options) {
return this.each(function() {
if (!$.data(this, pluginName)) {
$.data(this, pluginName, new Plugin(this, options));
}
});
};
// 暴露構造函數供高級用法
$[pluginName] = Plugin;
})(jQuery);
// 使用
$("#nav").scrollSpy({ offset: 50 });
// 獲取實例調用方法
var instance = $("#nav").data("scrollSpy");
instance.destroy();
| 錯誤 | 後果 | 正確做法 |
|---|---|---|
不返回 this |
破壞鏈式調用 | 除非需返回數據,否則 return this |
內部直接用 $ 而未 IIFE 隔離 |
與其他庫衝突 | ;(function($){...})(jQuery) |
| 不合併默認配置 | 用戶無法覆蓋部分選項 | $.extend({}, defaults, options) |
| 事件綁定不命名空間 | 銷毀時誤傷其他綁定 | .on("click." + pluginName, ...) / .off("." + pluginName) |
數據存儲用 .data(key, val) 但銷毀不清理 |
內存洩漏 | .removeData(pluginName) |
jquery.xxx.js;$、傳入 jQuery$.fn / $ 正確this 在 each 中指向 DOM,外層指向 jQuery 對象destroy 方法清理事件/數據.min.js 並保留版權註釋jQuery 插件開發的核心是「約定優於配置」:遵循官方規範,利用 $.extend 合併選項、.each() 遍歷元素、return this 保持鏈式、.data() 管理實例狀態、命名空間隔離事件。掌握這套模式,即可產出專業級、可維護、生態友好的插件。