我最喜歡的jQuery外掛程式模板

來源:互聯網
上載者:User

標籤:

  我使用jQuery已經有相當長的時間了,並且我會常常為它寫一些外掛程式(plugin)。我嘗試過用不同的方式去寫,現在這個模板是我最喜歡的:

 

123456789101112131415161718192021222324252627282930313233 ;(function($) {  // multiple plugins can go here  (function(pluginName) {    var defaults = {      color: ‘black‘,      testFor: function(div) {        return true;      }    };    $.fn[pluginName] = function(options) {      options = $.extend(true, {}, defaults, options);                   return this.each(function() {        var elem = this,          $elem = $(elem);         // heres the guts of the plugin          if (options.testFor(elem)) {            $elem.css({              borderWidth: 1,              borderStyle: ‘solid‘,              borderColor: options.color            });          }      });    };    $.fn[pluginName].defaults = defaults;    })(‘borderize‘);})(jQuery); //下面是用法$(‘div‘).borderize();$(‘div‘).borderize({color: ‘red‘});

  以下是我喜歡這種模板的原因

  1. 你仍然可以訪問裡面的預設選項,即便它被重寫了(簡單地通過父屬性的訪問)

  2. 通過修改pluginName即可更改外掛程式的名字。(這種方式對代碼壓縮也非常有利)

  第#1點非常強大,比如說我們希望複寫這個方法,但是仍然希望保留原來的方法,我們可以看下面的例子:

12345678910111213141516171819 $(‘.borderize‘).borderize({    testFor: function(elem) {        var $elem = $(elem);        if (elem.is(‘.inactive‘)) {            return false;        } else {            // calling "parent" function            return $.fn.borderize.defaults.testFor.apply(this, arguments);        }    }});We can even do this with regular properties like this var someVarThatMayBeSet = false;/* code ... */ $(‘.borderize‘).borderize({    color: someVarThatMayBeSet ? ‘red‘ : $.fn.borderize.defaults.color});

  你有更好的模板嗎?歡迎回複。

  原文 kolodny.github.io

我最喜歡的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.