自定義$插件注意事項

/*
注:1,命名:jquery.{diy}.js         
2, “jQuery.fn”是“jQuery.prototype”的簡寫  
3,自執行匿名函數(function(){代碼})();防止污染全局命名空間,同時不會和別的代碼衝突;
4,我們在代碼開頭加一個分號,防止別人使用時,別人的代碼方法後沒有分號而導致出錯;
5最後我們得到一個非常安全結構良好的代碼:加入window等是防止這些全局變量被別人污染;
    ; (function ($, window, document, undefined) {
        //我們的代碼。。
        //blah blah blah...
    })(jQuery, window, document);
6,當變量是jQuery類型時,建議以$開頭,如:var $element=$('a');
7,題外話:一般HTML代碼裏面使用雙引號,而在JavaScript中多用單引號
8,$.fn[pluginName]和$.fn.pluginName寫法不同,意義相同
*/
//1、封裝對象方法的插件,例如wdtree
//閉包限定命名空間
; (function ($) {
    $.fn.treeview = function (settings) {
        debugger
        var dfop = {
            color: '#ff9966'
        };
        var opts = $.extend({}, dfop, settings.options);//覆蓋默認配置,注:新的空對象做爲$.extend的第一個參數,defaults和用戶傳遞的參數對象緊隨其後,這樣做的好處是所有值被合併到這個空對象上,保護了插件裏面的默認值。
        return this.each(function () {      //加return可以使自定義的方法支持$鏈式調用
            var $this = $(this);
            $this.css({
                color: opts.color
            });
        });
    }
})(jQuery);
//2、封裝全局函數的插件,eg:jquery.validate.js


//閉包限定命名空間
; (function ($) {
    $.extend($.fn, {
        valid: function (a) {


        }
    });
})(jQuery);


//-----------------------------------------sliphover-----------------------------------------
; (function ($, window, document, undefined) {
    //定義Beautifier的構造函數
    var Beautifier = function (ele, opt) {
        this.$element = ele,
        this.defaults = {
            'color': 'red',
            'fontSize': '12px',
            'textDecoration': 'none'
        },
        this.options = $.extend({}, this.defaults, opt)
    }
    //定義Beautifier的方法
    Beautifier.prototype = {
        beautify: function () {
            return this.$element.css({
                'color': this.options.color,
                'fontSize': this.options.fontSize,
                'textDecoration': this.options.textDecoration
            });
        }
    }
    //在插件中使用Beautifier對象
    $.fn.myPlugin = function (options) {
        //創建Beautifier的實體
        var beautifier = new Beautifier(this, options);
        //調用其方法
        return beautifier.beautify();
    }
    //多個變量只需要一個var關鍵字就行了
    var c = 3,
        b = 5;
})(jQuery, window, document);

調用:

<script>
    $(function () {
        $('a').myPlugin({
            'color': '#2C9929',
            'fontSize': '20px',
            'textDecoration': 'underline'
        });
    })
</script>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章