1. 程式人生 > >封裝簡單的jquery外掛

封裝簡單的jquery外掛

接下來我們一起來寫個高亮的jqury外掛

1.定一個閉包區域,防止外掛"汙染"

//閉包限定名稱空間
(function ($) {
    
})(window.jQuery);

2.jQuery.fn.extend(object)擴充套件jquery 方法,製作外掛

//閉包限定名稱空間
(function ($) {
    $.fn.extend({
        "highLight":function(options){
            //do something
        }
    });
})(window.jQuery);

3.給外掛預設引數,實現 外掛的功能

//閉包限定名稱空間
(function ($) {
    $.fn.extend({
        "highLight": function (options) {
            var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆蓋外掛預設引數
            this.each(function () {  //這裡的this 就是 jQuery物件
                //遍歷所有的要高亮的dom,當呼叫 highLight()外掛的是一個集合的時候。
                var $this = $(this); //獲取當前dom 的 jQuery物件,這裡的this是當前迴圈的dom
                //根據引數來設定 dom的樣式
                $this.css({
                    backgroundColor: opts.background,
                    color: opts.foreground
                });
            });


        }
    });
    //預設引數
    var defaluts = {
        foreground: 'red',
        background: 'yellow'
    };
})(window.jQuery);

到這一步,高亮外掛基本功能已經具備了。呼叫程式碼如下:

$(function () {
    $("p").highLight(); //呼叫自定義 高亮外掛
});

完整的高亮外掛程式碼如下:

//閉包限定名稱空間
(function ($) {
    $.fn.extend({
        "highLight": function (options) {
            //檢測使用者傳進來的引數是否合法
            if (!isValid(options))
                return this;
            var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆蓋外掛預設引數
            return this.each(function () {  //這裡的this 就是 jQuery物件。這裡return 為了支援鏈式呼叫
                //遍歷所有的要高亮的dom,當呼叫 highLight()外掛的是一個集合的時候。
                var $this = $(this); //獲取當前dom 的 jQuery物件,這裡的this是當前迴圈的dom
                //根據引數來設定 dom的樣式
                $this.css({
                    backgroundColor: opts.background,
                    color: opts.foreground
                });
                //格式化高亮文字
                var markup = $this.html();
                markup = $.fn.highLight.format(markup);
                $this.html(markup);
            });


        }
    });
    //預設引數
    var defaluts = {
        foreground: 'red',
        background: 'yellow'
    };
    //公共的格式化 方法. 預設是加粗,使用者可以通過覆蓋該方法達到不同的格式化效果。
    $.fn.highLight.format = function (str) {
        return "<strong>" + str + "</strong>";
    }
    //私有方法,檢測引數是否合法
    function isValid(options) {
        return !options || (options && typeof options === "object") ? true : false;
    }
})(window.jQuery);
//呼叫
        //呼叫者覆蓋 外掛暴露的共公方法
        $.fn.highLight.format = function (txt) {
            return "<em>" + txt + "</em>"
        }
        $(function () {
            $("p").highLight({ foreground: 'orange', background: '#ccc' }); //呼叫自定義 高亮外掛
        });