第八周作業

來源:互聯網
上載者:User

標籤:

如何編寫jQuery自訂外掛程式

  最近瞭解到jQuery的兩種自訂外掛程式方法,一種是自訂對象級外掛程式方法,另一種是自訂類級外掛程式方法。

  以下是我對jQuery自訂外掛程式的瞭解與實踐,執行個體代碼是自己編寫的,有什麼不對的地方,請多多指點。


  (一)自訂對象級外掛程式有如下兩種形式:
    形式一:

(function($){        $.fn.extend({        pluginName:function(opt,callback){                              // Our plugin implementation code goes here.          }        })        })(jQuery);             

    形式二:

(function($) {     $.fn.pluginName = function() {         // Our plugin implementation code goes here.     }; })(jQuery);     

    對象級形式一(設定焦點顏色)外掛程式執行個體:

(function(){    $.fn.extend({        focusColor: function(li_col)    {            var def_col = "#ccc";    //預設擷取焦點的色值            var lst_col = "#fff";    //預設丟失焦點的色值            //如果設定的顏色不為空白,使用設定的顏色,否則為預設色            li_col = (li_color == undefined) ? del_col : li_col;            $(this).find("li").each(function(){    //遍曆表項<li>中的全部元素                $(this).mouseover(function() {    //擷取滑鼠焦時間點事件                    $(this).css("background-color",li_col);    //使用設定的顏色                }).mouseout(function() {    //滑鼠焦點移出事件                    $(this).css("background-color","#fff");    //恢複原來的顏色                });            });            return $(this);    //返回jQuery對象,儲存鍵式操作        }    });})(jQuery);

 

   (二)自訂類級外掛程式有如下形式:

jQuery.extend({     pluginName: function() {         // Our plugin implementation code goes here.     },     pluginName: function(param) {         // Our plugin implementation code goes here.     } });    

    類層級外掛程式(兩數相加/減)執行個體:

(function(){    $.extend({        addNum: function(p1,p2) {            //如果傳入的數字不為空白,使用傳入的數字,否則為0            p1 = (p1 == undefined) ? 0 : p1;            p2 = (p2 == undefined) ? 0 : p2;            var intResult = parseInt(p1) + parseInt(p2);            return intResult;        },        subNum: function(p1,p2) {            //如果傳入的數字不為空白,使用傳入的數字,否則為0            p1 = (p1 == undefined) ? 0 : p1;            p2 = (p2 == undefined) ? 0 : p2;            if(p1>p2) {                var intResult = parseInt(p1) - parseInt(p2);            }            return intResult;        }    });})(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.