萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

手把手教你開發 jQuery 插件:從入門到最佳實踐

插件分類

類型掛載位置調用方式典型場景
對象級插件$.fn$(selector).pluginName()DOM 元素增強(Tabs、Slider、表單驗證)
類級/全局函數$ / jQuery$.pluginName()工具函數($.ajax、$.each)
選擇器擴展$.expr[":"]$(":customSelector")自定義選擇器(:external、:containsEx)

對象級插件標準範本

;(function($, window, document, undefined) {
    "use strict";

    // 1. 插件名與預設配置
    const pluginName = "myPlugin";
    const defaults = {
        color: "red",
        speed: 300,
        onComplete: $.noop
    };

    // 2. 建構函數
    function Plugin(element, options) {
        this.element = element;
        this.$element = $(element);
        this.settings = $.extend({}, defaults, options);
        this._name = pluginName;
        this.init();
    }

    // 3. 原型方法
    $.extend(Plugin.prototype, {
        init() {
            this.bindEvents();
            this.render();
        },
        bindEvents() {
            this.$element.on("click." + pluginName, () => this.handleClick());
        },
        render() {
            this.$element.css("color", this.settings.color);
        },
        handleClick() {
            this.$element.fadeOut(this.settings.speed, () => {
                this.$element.fadeIn(this.settings.speed);
                this.settings.onComplete.call(this.element);
            });
        },
        destroy() {
            this.$element.off("." + pluginName);
            this.$element.removeData(pluginName);
        }
    });

    // 4. 掛載到 $.fn,防止重複實例化
    $.fn[pluginName] = function(options) {
        const args = arguments;
        return this.each(function() {
            const $this = $(this);
            let instance = $this.data(pluginName);

            if (!instance) {
                // 初始化
                if (typeof options === "object" || !options) {
                    instance = new Plugin(this, options);
                    $this.data(pluginName, instance);
                }
            } else if (typeof options === "string") {
                // 呼叫實例方法
                if (options === "destroy") {
                    instance.destroy();
                    $this.removeData(pluginName);
                } else if (typeof instance[options] === "function") {
                    instance[options].apply(instance, Array.prototype.slice.call(args, 1));
                }
            }
        });
    };
})(jQuery, window, document);

關鍵最佳實踐解析

1. 立即執行函數 (IIFE) + 傳參

;(function($, window, document, undefined) { ... })(jQuery, window, document);

  • 前置分號防止合併壓縮時上一行遺漏分號導致語法錯誤
  • 參數化 undefined 保證 ES3 環境下 undefined 未被篡改
  • 局部變量壓縮更優(window → w)

2. 命名空間事件

click.myPlugin、resize.myPlugin —— destroy() 時 off(".myPlugin") 一次清理所有,不影響其他綁定。

3. 數據緩存 .data()

實例掛載在元素 data 上,避免全局變量污染,支援多實例獨立狀態。

4. 方法調用模式

// 初始化
$("#elem").myPlugin({ color: "blue" });

// 呼叫實例方法
$("#elem").myPlugin("destroy");
$("#elem").myPlugin("handleClick"); // 無參方法

// 獲取實例(進階)
const instance = $("#elem").data("myPlugin");
instance.settings.speed = 500;

5. 配置合併 $.extend

// 深度合併:$.extend(true, {}, defaults, options)
// 淺層合併(常用):$.extend({}, defaults, options)
// 多對象合併:$.extend({}, defaults, options1, options2)

類級插件(全局函數)

;(function($) {
    $.myUtil = {
        formatDate(date, fmt) { /* ... */ },
        debounce(fn, delay) { /* ... */ }
    };
    // 或直接掛函數
    $.showMsg = function(msg) { alert(msg); };
})(jQuery);

// 使用
$.myUtil.formatDate(new Date(), "yyyy-MM-dd");
$.showMsg("Hello");

發佈前檢查清單

  • [ ] 檔案命名:jquery.myPlugin.js / jquery.myPlugin.min.js
  • [ ] 相容 noConflict 模式(使用 jQuery 而非 $)
  • [ ] 支援 AMD/CommonJS/ESM(UMD 封裝)
  • [ ] 文檔:README、選項表、方法表、事件表、範例
  • [ ] 單元測試(QUnit/Jest)
  • [ ] 語義化版本號

現代替代方案

新專案建議直接編寫 原生 JS Class/ES Module,無需 jQuery 依賴:

// my-plugin.js
export class MyPlugin {
    constructor(element, options) { /* ... */ }
    init() { /* ... */ }
    destroy() { /* ... */ }
}

// 使用
import { MyPlugin } from "./my-plugin.js";
new MyPlugin(document.querySelector("#elem"), { color: "blue" });
copyright © 萬盛學電腦網 all rights reserved