zoukankan      html  css  js  c++  java
  • 我最喜欢的jQuery插件模板

      我使用jQuery已经有相当长的时间了,并且我会常常为它写一些插件(plugin)。我尝试过用不同的方式去写,现在这个模板是我最喜欢的:

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    ;(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点非常强大,比如说我们希望复写这个方法,但是仍然希望保留原来的方法,我们可以看下面的例子:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    $('.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

  • 相关阅读:
    关于asp.net Ajax v1.0.61025版(即1.0 rc) 错误:'sys'未定义解决方法.
    MagicAjax Features (MagicAjax特点 0.30版) (翻译)
    简单测试在存储过程中临时表与union all的性能差别
    Reporting Service 中使用自定义程序集
    vs.net Ide智能感知自动失效后处理
    关于ie的内存泄漏与javascript内存释放
    无代码的工作流创作模式
    工作流服务Workflow Service(2):SendActivity
    推荐一个操作Zip文件的开源类库:DotNetZip
    工作流与WF
  • 原文地址:https://www.cnblogs.com/xiaochao12345/p/4210856.html
Copyright © 2011-2022 走看看