書上說「維護鏈式調用」,但 this 本身就是 jQuery 物件,為何還要 .each()?
// jQuery 核心原始碼簡化
$.fn.myPlugin = function(options) {
return this.each(function() {
// 這裡的 this 是「單一 DOM 元素」
// 對每個元素做初始化、綁定事件等
var $el = $(this);
$el.data('myPlugin', new MyPlugin($el, options));
});
// each() 結束後回傳原始 jQuery 物件(this),保持鏈式
};
| 寫法 | 行為 | 適用場景 |
|---|---|---|
return this; | 直接回傳集合,**不執行**任何逐元素邏輯 | 單純包裝器、無需逐元素操作 |
return this.each(...) | **遍歷每個元素**執行回調,最後回傳集合 | 插件初始化、逐元素綁定、資料掛載 |
// ❌ 錯誤示範:this 是 jQuery 集合,非單一元素
$.fn.badPlugin = function() {
this.css('color', 'red'); // 這行其實會對集合所有元素生效,因為 css() 內部用 each()
return this;
};
// ✅ 標準寫法:明確語意,未來好維護
$.fn.goodPlugin = function() {
return this.each(function() {
// 這裡可針對單一元素做複雜邏輯
$(this).css('color', 'red');
});
};
this.each(fn) = 遍歷執行 fn + 回傳 this。return this.each(...),確保:$('.box').myPlugin().fadeIn())。