DIV CSS 佈局教程網

jQuery 插件開發范例代碼解析
編輯:JQuery特效代碼     

編寫一個結構規范的 jQuery 插件,通常需要遵循一定的模式:用閉包包裹防止全局變量污染、通過 $.extend 合併默認配置、使用 each 遍歷匹配元素,並將一些工具函數封裝為可對外暴露的方法。下面是一個典型的插件范例:

// 創建一個閉包
(function ($) {
    // 插件的定義
    $.fn.hilight = function (options) {
        debug(this);
        // build main options before element iteration
        var opts = $.extend({}, $.fn.hilight.defaults, options);
        // iterate and reformat each matched element
        return this.each(function () {
            $this = $(this);
            // build element specific options
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
            // update element styles
            $this.css({
                backgroundColor: o.background,
                color: o.foreground
            });
            var markup = $this.html();
            // call our format function
            markup = $.fn.hilight.format(markup);
            $this.html(markup);
        });
    };
    // 私有函數:debugging
    function debug($obj) {
        if (window.console && window.console.log)
            window.console.log('hilight selection count: ' + $obj.size());
    };
    // 定義暴露 format 函數
    $.fn.hilight.format = function (txt) {
        return '<strong>' + txt + '</strong>';
    };
    // 插件的 defaults
    $.fn.hilight.defaults = {
        foreground: 'red',
        background: 'yellow'
    };
// 閉包結束
})(jQuery);

代碼要點解析

  • 閉包結構:整個插件包裹在 (function($){ ... })(jQuery) 中,將 jQuery 作為參數傳入,避免與其他庫的 $ 沖突,同時隔離私有變量。
  • 配置合併:通過 $.extend({}, $.fn.hilight.defaults, options) 將用戶傳入的 options 與默認配置合併,實現靈活的參數定製。
  • 遍歷元素:使用 this.each() 遍歷所有匹配元素,支持鏈式調用,讓插件可以同時作用於多個元素。
  • 私有函數:debug() 作為私有函數封裝在閉包內部,不污染全局作用域。
  • 暴露公共方法:通過 $.fn.hilight.format 將 format 方法掛載到插件上,方便外部調用擴展。
  • 默認配置:將默認值集中在 $.fn.hilight.defaults 中,便於維護與閱讀。

掌握這套標準化的插件編寫模式,就能寫出結構清晰、易於維護和複用的高質量 jQuery 插件。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved