$ =JQuery,以下就用$表示。
$.fn.extend 和$.extend是JQuery提供的兩種擴展插件的方法。
<div id="testDiv"></div>
(function( $, window, document, undefined ){}){
$.fn.extend({
test:function(){
alert($(this).attr("id"));
}
});
}(jquery,window,document)
$("#testDiv").test();
//結果:testDiv
(function( $, window, document, undefined ){}){
$.extend({
test:function(){
alert("第二個");
}
});
}(jquery,window,document)
$('#testDiv').test();
//結果:第二個
示例中第一個方法是綁定在dom上的插件,第二個是綁定在JQuery上的插件。
第一種方法適用於自己編寫插件,比如編寫個彈窗插件,綁定時間後點擊按鈕仍然可以調用插件方法。
第二種方法是給JQuery本身添加靜態方法。
$.fn.extend(fangfa) = $.prototype.extend(fangfa) = $.fn.fangfa
封裝插件的一個小示例:
(function($,window,document){
var methods = {
init: function (options) {//初始化方法
var settings = $.extend({
...//初始化傳入的參數
},options);
return this.each(function(){
function a(){
getAllPageData();
}
})
},
a: function () {//可調用a方法
...
},
b: function () {//可調用b方法
...
}
}
$.fn.zjmxxx= function (method) {
if(methods[method]){
return methods[method].apply(this, Array.prototype.slice.call(arguments,1))
}else if(typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
}else{
$.error('Method'+method+'does not exist on jQuery.zjmxxx');
}
}
})(jQuery,window,document);
通過$('選擇器').zjmxxx.({初始化參數})————調用的是init初始化方法,
通過$('選擇器').zjmxxx.('a')————調用的是a方法,
zjmxxx可以自己命名成自己想要的方法名