萬盛學電腦網

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

jQuery 插件開發完整教學:全域函式、實例方法與最佳實踐模式

擴充方式總覽

類型掛載位置呼叫方式適用場景
全域函式jQuery.fn / jQuery$.fn.method() / $.method()工具函式、命名空間管理
實例方法jQuery.fn$(selector).method()DOM 元素操作、鏈式呼叫

一、全域函式擴充

1.1 直接掛載

jQuery.sayHello = function(name) {
  alert(name + ' 您好');
};

// 呼叫
$.sayHello('小明'); // 或 jQuery.sayHello('小明')

1.2 使用 jQuery.extend() 批次擴充

jQuery.extend({
  min: function(a, b) { return a < b ? a : b; },
  max: function(a, b) { return a > b ? a : b; }
});

$.min(2, 3); // 2
$.max(4, 5); // 5

jQuery.extend(object) 直接擴充 jQuery 命名空間本身。

二、實例方法擴充(核心:jQuery.fn)

2.1 基礎寫法

jQuery.fn.sayHello = function(name) {
  return this.each(function() {
    alert(name + ' 您好,我是 ' + this.tagName);
  });
};

// 呼叫:針對每個匹配元素執行
$('div').sayHello('訪客');
關鍵:回傳 this(jQuery 物件)以支援鏈式呼叫;內部用 this.each() 遍歷匹配集合。

2.2 jQuery.fn.extend() 批次新增插件

jQuery.fn.extend({
  check: function() {
    return this.each(function() { this.checked = true; });
  },
  uncheck: function() {
    return this.each(function() { this.checked = false; });
  }
});

// 使用
$('input[type=checkbox]').check();
$('input[type=radio]').uncheck();

三、專業插件開發模板(含預設值、銷毀、事件命名空間)

(function($) {
  var pluginName = 'myPlugin';
  var defaults = {
    color: 'red',
    speed: 300,
    onComplete: $.noop
  };

  function Plugin(element, options) {
    this.element = element;
    this.$el = $(element);
    this.settings = $.extend({}, defaults, options);
    this._init();
  }

  Plugin.prototype = {
    _init: function() {
      this.$el.css('color', this.settings.color);
      this._bindEvents();
    },
    _bindEvents: function() {
      this.$el.on('click.' + pluginName, $.proxy(this._onClick, this));
    },
    _onClick: function() {
      this.$el.fadeOut(this.settings.speed, this.settings.onComplete);
    },
    destroy: function() {
      this.$el.off('.' + pluginName).removeData(pluginName);
    }
  };

  // 掛載至 jQuery.fn
  $.fn[pluginName] = function(options) {
    var args = Array.prototype.slice.call(arguments, 1);
    return this.each(function() {
      var instance = $.data(this, pluginName);
      if (!instance) {
        instance = new Plugin(this, options);
        $.data(this, pluginName, instance);
      }
      if (typeof options === 'string' && typeof instance[options] === 'function') {
        instance[options].apply(instance, args);
      }
    });
  };
})(jQuery);

// 使用範例
$('.box').myPlugin({ color: 'blue', speed: 500 });
$('.box').myPlugin('destroy');

四、插件開發黃金法則

  1. 維持鏈式:永遠回傳 this(除非刻意回傳特定值)。
  2. 保護預設值:使用 $.extend({}, defaults, options) 避免污染預設物件。
  3. 命名空間事件:.on('click.myplugin'),銷毀時精準解綁。
  4. 資料儲存用 .data():實例掛載於元素,避免全域變數污染。
  5. 支援方法呼叫:$(sel).plugin('method', arg) 模式。
  6. IIFE 包裹:避免全域變數洩漏,傳入 $ 參數相容 noConflict。
copyright © 萬盛學電腦網 all rights reserved