jQuery插件機制


/*
 
 * 自定義jQuery插件,經過擴展JQuery對象自己進行擴展。
 * 一、能夠經過一個當即執行函數 而後在使用$.extend({...}); 對$對象自己進行擴展
 * 調用時能夠經過$.xxx(),$.xxx 調用到擴展方法及屬性
 * 
 * 爲了使得$被從新定義,出現衝突,致使沒法使用,
 * 咱們在匿名函數中以$爲形參,調用時使用jQuery做爲實參.
 * 
 * 
 * */
(function($){
    $.extend({
        minValue:function(a,b){
            return a > b ? b : a;
        },
        MY_PI:3.141592654875641
    });
})(jQuery);dom

/*
 * 二、擴展jQuery對象.
 * 調用時須要先獲取到jQuery對象,而後進行調用
 * $("xxx").yyy();
 * */
(function($){
    $.fn.extend({
        sayHello:function(){
            return "hello 你們好,我是一個插件方法";
        },
        //給jQuery的對象擴展全選功能,
        checkAll:function(){
            this.each(function(){  // 當前this是jQuery對象
                this.checked = true; // 此時的this是dom元素
            });
        },
        reverseCheck:function(){
            this.each(function(){  // 當前this是jQuery對象
                this.checked = !this.checked;
            });
        }
    });
})(jQuery);
 函數

相關文章
相關標籤/搜索