萬盛學電腦網

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

jQuery 插件開發:擴展自定義方法實現表單元素禁用功能

為什麼要擴展 jQuery?

jQuery 核心庫不包含禁用表單元素的便捷方法。通過 jQuery.fn.extend() 或直接賦值 jQuery.fn.disable = ...,可將自定義邏輯融入鏈式調用,提升代碼復用性與可讀性。

插件開發標準模板

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

  // 插件名
  var pluginName = 'disable';

  // 默認配置
  var defaults = {
    disabledClass: 'disabled', // 附加樣式類
    disableAttr: true,         // 是否設置 disabled 屬性
    callback: null             // 禁用後回調
  };

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

  // 原型方法
  Plugin.prototype = {
    init: function () {
      var $el = $(this.element);
      var opts = this.settings;

      // 核心邏輯:遍歷匹配元素
      $el.each(function () {
        var $this = $(this);

        // 1. 設置 disabled 屬性(原生表單元素)
        if (opts.disableAttr && this.tagName.match(/^(input|select|textarea|button)$/i)) {
          this.disabled = true;
        }

        // 2. 添加樣式類(統一視覺反饋)
        if (opts.disabledClass) {
          $this.addClass(opts.disabledClass);
        }

        // 3. 阻止交互事件(針對非表單元素如 a、div)
        $this.on('click.disable mousedown.disable keydown.disable', function (e) {
          e.preventDefault();
          e.stopPropagation();
          return false;
        });
      });

      // 觸發回調
      if ($.isFunction(opts.callback)) {
        opts.callback.call(this, $el);
      }
    },

    // 銷毀方法:恢復狀態
    destroy: function () {
      var $el = $(this.element);
      var opts = this.settings;

      $el.each(function () {
        if (opts.disableAttr && this.tagName.match(/^(input|select|textarea|button)$/i)) {
          this.disabled = false;
        }
        if (opts.disabledClass) {
          $el.removeClass(opts.disabledClass);
        }
        $el.off('.disable'); // 移除命名空間事件
      });
    }
  };

  // 掛載到 jQuery.fn
  $.fn[pluginName] = function (options) {
    var args = arguments;
    var isMethodCall = typeof options === 'string';

    // 支持鏈式調用
    return this.each(function () {
      var $this = $(this);
      var instance = $this.data(pluginName);

      if (isMethodCall) {
        // 調用實例方法:$('#form').disable('destroy')
        if (instance && typeof instance[options] === 'function') {
          instance[options].apply(instance, Array.prototype.slice.call(args, 1));
        }
      } else {
        // 初始化或覆蓋配置
        if (!instance) {
          $this.data(pluginName, new Plugin(this, options));
        } else {
          instance.init.call($.extend(instance, { settings: $.extend({}, instance.settings, options) }));
        }
      }
    });
  };
})(jQuery, window, document);

使用示例

<form id="myForm">
  <input type="text" placeholder="用戶名" />
  <input type="password" placeholder="密碼" />
  <button type="submit" class="btn-primary">登錄</button>
  <a href="#" class="btn-link">忘記密碼</a>
</form>

<script>
// 1. 基礎用法:禁用整個表單
$('#myForm').find('input, button, a').disable();

// 2. 自定義配置
$('button.submit').disable({
  disabledClass: 'btn-disabled',
  disableAttr: true,
  callback: function ($els) {
    console.log('已禁用元素數量:', $els.length);
  }
});

// 3. 動態啟用(調用 destroy)
setTimeout(function () {
  $('#myForm').find('input, button, a').disable('destroy');
}, 5000);

// 4. 針對特定選擇器
$('form input.required').disable(); // 只禁用必填項

CSS 配合樣式

.disabled,
input.disabled,
button.disabled,
a.disabled {
  opacity: 0.6;
  cursor: not-allowed;
  background-color: #f5f5f5 !important;
  border-color: #ddd !important;
  color: #999 !important;
}

// 針對 a 標簽的禁用狀態
a.disabled {
  pointer-events: none; /* 現代瀏覽器直接阻止點擊 */
}

進階:表單級禁用插件

$.fn.disableForm = function (options) {
  return this.each(function () {
    var $form = $(this);
    // 禁用所有表單控件
    $form.find('input, select, textarea, button').disable(options);
    // 阻止表單提交
    $form.off('submit.disable').on('submit.disable', function (e) {
      e.preventDefault();
    });
  });
};

// 使用
$('#myForm').disableForm({ disabledClass: 'form-disabled' });

插件開發最佳實踐清單

原則說明
IIFE 隔離作用域防止全局變量污染,傳入 $, window, document 參數
使用 'use strict'啟用嚴格模式,捕獲常見錯誤
支持配置選項合並$.extend({}, defaults, options) 保護默認值
維護鏈式調用返回 this.each(...) 支持 $().disable().css()...
數據緩存實例.data(pluginName, instance) 支持後續方法調用
命名空間事件.on('click.disable') 精確移除不影響其他綁定
提供 destroy 方法清理事件、數據、樣式,防止內存洩漏
兼容 AMD/CMD/ESM頭部添加 UMD 判斷,適配各類模塊系統

總結

jQuery 插件機制讓我們能將重複的 DOM 操作邏輯封裝為可配置、可復用、可鏈式調用的組件。本文以 .disable() 為例,展示了從簡單擴展到完整插件架構的演進過程。掌握這套模式,即可將項目中常見的「表單驗證彈窗、圖片懶加載、無限滾動、模態框」等業務邏輯標準化為團隊通用組件庫。

copyright © 萬盛學電腦網 all rights reserved