Jquery自定義插件之$.extend()、$.fn和$.fn.extend()


jquery插件的種類:

  1.對象級別的插件開發,即給jQuery對象添加方法,封裝對象方法的插件,如:parent()、appendTo()

  2.一種是類級別的插件開發,即給jQuery添加新的全局函數,相當於給jQuery類本身添加方法,jQuery的全局函數就是屬於jQuery命        名空間的函數,封裝全局函數的插件

  3.選擇器插件

jQuery插件機制

  jQuery為開發插件提拱了兩個方法,分別是:

     jQuery.fn.extend(object); 給jQuery對象添加方法。

     jQuery.extend(object); 為擴展jQuery類本身.為類添加新的方法,可以理解為添加靜態方法。

     這兩個方法都接受一個參數,類型為Object,Object對應的"名/值對"分別代表"函數或方法體/函數主體"。

 

1.對象級別的插件開發,

  這里的方法提供一個參數value,如果調用方法時傳入value,那么就用這個值來設置字體顏色,否則就是獲取匹配無此的字體顏色的值

<span style="font-size:12px;">;(function($){  
    $.fn.extend({  
        "color":function(value){  
            return this.css("color",value);  
        }  
    });  
})(jQuery);</span>  
 調用時可直接寫成:$("div").color("red");
另外如果要定義一組插件,可以使用如下所示寫法:
<span style="font-size:12px;">;(function($){  
    $.fn.extend({  
        "color":function(value){ //這里寫插件代碼  }, "border":function(value){ //這里寫插件代碼  }, "background":function(value){ //這里寫插件代碼  } }); })(jQuery);</span> 
添加jQuery對象級的插件,是給jQuery類添加方法
;(function($){  
    $.fn.extend({  
        "函數名":function(自定義參數){ //這里寫插件代碼  } }); })(jQuery); 或者 ;(function($){ $.fn.函數名=function(自定義參數){ //這里寫插件代碼  } })(jQuery); 調用方法:$("#id").函數名(參數);

 

2.類級別的插件開發,封裝全局函數的插件

例如新增兩個函數,用於去除左側和右側的空格。

<span style="font-size:12px;">;(function($){  
    $.extend({  
        ltrim:function(text){  
            return (text||"").replace(/^\s+g,"");  
        },  
        rtrim:function(text){  
            return (text||"").replace(/\s+$/g,"");  
        }  
    });  
})(jQuery);  
或者  
;(function($){  
    $.ltrim=function(text){  
        return (text||"").replace(/^\s+g,"");  
    },  
    $.rtrim=function(text){  
        return (text||"").replace(/\s+$/g,"");  
    }  
      
})(jQuery);</span> 

 調用函數:

<span style="font-size:12px;">$("trimTest").val(
    jQuery.trim(" test ")+"\n"+ jQuery.ltrim(" test ")+"\n"+ jQuery.rtrim(" test ") );</span> 
文本框中第一行字符串左右兩側的空格都被刪除。
 第二行的字符串只有左側的空格被刪除。
 第三行的字符串只有右側的空格被刪除。


.jQuery類級別的插件,相當於添加靜態方法
;(function($){  
    $.extend({  
        "函數名":function(自定義參數){ //這里寫插件代碼  } }); })(jQuery); 或者 ;(function($){ $.函數名=function(自定義參數){ //這里寫插件代碼  } })(jQuery); 調用方法:$.函數名(參數);

 

使用jQuery.extend(object)添加全局函數

jQuery.extend({
    foo:function(){
        alert("This is a test.");    
    },
    bar:function(){
       alert("This is another test");
    }
});

  

添加一個新的全局函數,我們只需如下定義:

jQuery.foo = function() {   
 alert("This is a test.");  
 }; 

增加多個全局函數

添加多個全局函數,可采用如下定義:

jQuery.foo = function(){
  alert("This is a test.");  
};
jQuery.bar = function(param){
    alert("This is another test.");
}

調用時和一個函數的一樣的:jQuery.foo(); jQuery.bar(); 簡寫形式為:$.foo(); $.bar("bar");

 

 使用命名空間

jQuery.myPlugin = {
    foo:function(){
       alert("This is a test."); } , bar:function("bar"){ alert("This is another test."); } } 采用命名空間的函數仍然是全局函數,調用時采用的方法: jQuery.myPlugin.foo(); jQuery.myPlugin.bar("bar"); 簡寫形式為: $.myPlugin.foo(); $.myPlugin.bar("bar"); 通過這個技巧(使用獨立的插件名),我們可以避免命名空間內函數的沖突。

 

雖然在jQuery命名空間中,我們禁止使用javascript函數名和變量名。但仍然不可避免某些函數名或變量名將與其他jQuery插件沖突,因此我們習慣將一些方法封裝到另一個自定義的命名空間。
$.fn.extend是一個實例的擴展,但是$.extend是類的擴展
<script type="text/javascript"> (function($){ $.fn.extend({ myPlugName:function(){ $(this).click(function(){ alert($(this).val()); }); } }); })(jQuery); </script>

<body>
    <input type="button" value="點擊我" id="btn" />
</body> <script type="text/javascript"> $("#btn").myPlugName(); </script>



    <script type="text/javascript">
        (function($){
            $.fn.hilight=function(options){ var defaults={ foreground:'red', background:'yellow' }; var opts = $.extend(defaults,options); $(this).css("background-color",opts.background); $(this).css("color",opts.foreground); }; })(jQuery); </script> <body> <div id="myDiv">This is a Params JQuery!</div> </body> <script type="text/javascript"> $("#myDiv").hilight({foreground:'blue'}); </script>

var opts = $.extend(defaults,options);這句話的意思是吧defaults的屬性和options的屬性合並並保存到opts中 不懂的話參考:http://api.jquery.com/jQuery.extend/

 

暴露插件的默認設置

 

我們對上面代碼的一種改進是暴露插件的默認設置,這有利於讓插件的使用者更容易用較少的代碼覆蓋和修改插件,接下來我們開始利用函數對象。

// plugin definition
$.fn.hilight = function(options){
  // extend our default options with those provided.
  // note that the first arg to extend is an empty object , this is to keep form overriding our "defaults" object.
  var opts = $.extend({},$options);
// our plugin inplementation code goes here.  
};
// plugin defaults -added as a property on our plugin function
$.fn.hilight.default = {
    foreground : "red",
    background:"yellow"    
};
// 這個只需要調用一次,且不一定要在ready塊中調用
$.fn.hilight.defaults.foreground = "blue";
我們像這樣使用插件的方法,結果它設置藍色的前景色:
$("myDiv").hilight();

 

 

由於美元符號(“$”)不僅僅只有jQuery庫會使用到,其他Javascript庫也可能使用到,假如其他庫中“$”也有特別的含義,那么就會引起不必要沖突了,

下面定義了一個jQuery函數,形參是$,函數定義完成后,把jQuery這個實參傳遞進去,立即調用執行,這樣的好處是我們在寫jQuery插件時,也可以使用$這個別名,而不會與prototype引起沖突。

(function($) {
    $.fn.myPluginName = function() {
        // your plugin logic
    };
})(jQuery);


3、總結

jQuery為開發插件提拱了兩個方法,分別是:

jQuery.fn.extend(object);  給jQuery對象添加方法。
jQuery.extend(object);  為擴展jQuery類本身.為類添加新的方法。

3.1 jQuery.fn.extend(object);

fn 是什么東西呢。查看jQuery代碼,就不難發現。

jQuery.fn = jQuery.prototype = {  

init: function( selector, context ) {//....   

//......  

}; 

原來 jQuery.fn = jQuery.prototype.對prototype肯定不會陌生啦。雖然 javascript 沒有明確的類的概念,但是用類來理解它,會更方便。jQuery便是一個封裝得非常好的類,比如我們用 語句 $("#btn1") 會生成一個 jQuery類的實例。

jQuery.fn.extend(object); 對jQuery.prototype進得擴展,就是為jQuery類添加“成員函數”。jQuery類的實例可以使用這個“成員函數”。

$.fn是指jQuery的命名空間,加上fn上的方法及屬性,會對jquery實例每一個有效,如擴展$.fn.abc()是對jquery擴展了一個abc方法,那么后面的每個jQuery實例都可以引用這個方法了。

你可以這樣:$("myDiv").abc();

比如我們要開發一個插件,做一個特殊的編輯框,當它被點擊時,便alert 當前編輯框里的內容。可以這么做:

$.fn.extend({    
     alertWhileClick:function(){  
         $(this).click(function(){  
              alert($(this).val());  
          });   
      }   
});   

$("#input1").alertWhileClick();
 //頁面上為:
<input id="input1" type="text"/>

3.2 jQuery.extend(object); 

為jQuery類添加添加類方法,可以理解為添加靜態方法。如:

$.extend({  

    add:function(a,b){return a+b;}  

});  

便為 jQuery 添加一個為 add 的 “靜態方法”,之后便可以在引入 jQuery 的地方,使用這個方法了

$.add(3,4);

//return 7

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM