jQuery外掛程式開發

來源:互聯網
上載者:User

標籤:

一、開發方式:

1.類層級組件開發

  - 即在jQuery命名空間下添加新的全域函數,也稱為靜態方法。

  具體方法如下:

jQuery.myPlugin = function(){    // do something    }

  例如:$.ajax()、$.extend()

2.對象層級組件開發

  - 即掛在jQuery原型下的方法,這樣通過選取器擷取的jQuery對象執行個體也能共用該方法,也稱為動態方法。

  具體方法如下:

$.prototype.myPlugin = function(){    // do something}

 

二、鏈式調用:

 

$.fn.myPlugin = function (){    return this.each(function(){        //do something    })  }

 

    鏈式調用是jQuery的特點,實現鏈式調用的方法就是return this返回當前對象,上面的代碼中用了each方法來迴圈實現每個對象的訪問。

 

- 單例模式的動態方法:

$.fn.MyPlugin = function(){    var me = $(this),        instance = me.data("myPlugin");   //利用data()來存放外掛程式對象的執行個體    //如果執行個體存在就不重新建立,如果不存在就建立      if(!instence){        me.data("myPlugin",(instance = new myPlugin()));    }}

 

總結:一個單例模式jQuery外掛程式的架構可以這樣寫:

//建立一個閉包,形參是$,實參是jQuery(function($){  //私人方法  var privateFun = function(){ }
  var PageSlide = (function(){    //更改對象    function PageSlide(element,options){      this.settings = $.extend(true,$.fn.PageSlide.default,options||{});      this.element = element;      this.init();    }
    PageSlide.prototype
= {
      // 初始化方法      init :
function(){ }    }

  return PageSlide;})();//預設參數$.fn.PageSlide = function(options){  //實現鏈式調用  return this.each(function(){    var _self = $(this),      instance = _self.data(‘PageSlide‘);//存放外掛程式執行個體    if (!instance) {      instance = new PageSlide(_self,options);      _self.data(‘PageSlide‘,instance);    }      if ($.type(options)==‘string‘) return instance[options]();  });} //配置預設參數

$.fn.PageSlide.default = { }})(jQuery);

jQuery的$.extend()方法能夠將預設參數與自訂參數合并,當有ture時是深拷貝,沒有true時是淺拷貝。

 

jQuery外掛程式開發

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.