jQuery.extend()、jQuery.fn.extend()擴充方法樣本詳解

來源:互聯網
上載者:User

標籤:lin   type   select   tor   text   cti   包括   prot   test   

jQuery自訂了jQuery.extend()和jQuery.fn.extend()方法.

其中jQuery.extend()方法能夠建立全域函數或者選取器,

而jQuery.fn.extend()方法能夠建立jQuery對象方法. 

例如: 

複製代碼代碼如下:
jQuery.extend({ 
showName : function(name){ 
alert(name) 

}); 
jQuery.showName("深藍"); 


jQuery.extend()除了可以建立外掛程式外,還可以用來擴充jQuery對象. 
例如: 

複製代碼代碼如下:
var a = { 
name : "blue", 
pass : 123 

var b = { 
name : "red", 
pass : 456, 
age : 1 

var c = jQuery.extend({},a,b); 


c擁有a,b對象的屬性,由於,b對象在a對象之後,其name屬性優先在c對象裡. 

jQuery.extend()方法為外掛程式傳遞系列選項,包括預設值. 

複製代碼代碼如下:
function fn(options){ 
var options = jQuery.extend({ //預設參數選項列表 
name1 : value1, 
name2 : value2, 
name3 : value3 
},options); //使用函數的參數覆蓋或合并到預設參數選項列表中 
//函數體 

fn({ name1 : value3, name2 : value2 , name3 : value1 });//使用新值 
fn({ name4 : value3, name5 : value2 });//在預設上添加新選項 
fn(); //保持預設選項值 


當在調用該方法時,傳遞新的參數值,就會覆蓋掉預設的參數選項值,否則,使用預設參數值. 

使用JQuery.fn對象建立JQuery對象方法 

可以通過jQuery.fn對象來添加屬性和方法,實際上jQuery.fn對象就是掛接在jQuery.prototype上的,jQuery把它簡寫了. 

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

複製代碼代碼如下:
jQuery.fn = jQuery.prototype = { 

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

   //...... 

}; 


原來 jQuery.fn = jQuery.prototype.對prototype肯定不會陌生啦。 

例如: 

複製代碼代碼如下:
jQuery.fn.test = function(){ 
alert("這是jQuery對象方法!"); 

jQuery("div").click(function(){ 
$(this).test(); //在當前的jQuery對象上調用test()方法 
}); 


我們可以調用jQuery.fn.extend()方法來建立jQuery對象方法. 

複製代碼代碼如下:
jQuery.fn.extend({ 
test : function(){ 
return this.each(function(){ 
alert(this.nodeName) 
}); 

}); 
jQuery("body *").click(function(){ 
$(this).test(); //調用jQuery對象方法 
}); 


一句話:jQuery.extend是對JQuery類的自訂擴充,jQuery.fn.extend是對JQuery對象的自訂擴充.

jQuery.extend()、jQuery.fn.extend()擴充方法樣本詳解

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.