jQuery插件開發的兩種方法及$.fn.extend的詳解

jQuery插件開發分爲兩種: 

1 類級別 

類級別你能夠理解爲拓展jquery類,最明顯的例子是$.ajax(...),至關於靜態方法。 

開發擴展其方法時使用$.extend方法,即jQuery.extend(object); 
複製代碼代碼以下:

$.extend({ 

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

minus:function(a,b){return a-b;} 
}); 

頁面中調用: 
複製代碼代碼以下:

var i = $.add(3,2); 
var j = $.minus(3,2); 

2 對象級別 

對象級別則能夠理解爲基於對象的拓展,如$("#table").changeColor(...); 這裏這個changeColor呢,就是基於對象的拓展了。 

開發擴展其方法時使用$.fn.extend方法,即jQuery.fn.extend(object); 
複製代碼代碼以下:

$.fn.extend({ 

check:function(){ 
return this.each({ 
this.checked=true; 
}); 
}, 
uncheck:function(){ 
return this.each({ 
this.checked=false; 
}); 

}); 

頁面中調用: 
複製代碼代碼以下:

$('input[type=checkbox]').check(); 
$('input[type=checkbox]').uncheck(); 

三、擴展 
複製代碼代碼以下:
$.xy = {  add:function(a,b){return a+b;} ,  minus:function(a,b){return a-b;},  voidMethod:function(){ alert("void"); }  };  var i = $.xy.add(3,2);  var m = $.xy.minus(3,2);  $.xy.voidMethod(); 
相關文章
相關標籤/搜索