您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

推荐一款jQuery插件模板_jquery

2024/3/12 0:11:22发布17次查看
我使用jquery已经有相当长的时间了,并且我会常常为它写一些插件(plugin)。我尝试过用不同的方式去写,现在这个模板是我最喜欢的:
复制代码 代码如下:
;(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点非常强大,比如说我们希望复写这个方法,但是仍然希望保留原来的方法,我们可以看下面的例子:
复制代码 代码如下:
$('.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
});
小伙伴们,你们也会喜欢上这款jquery插件模板的吧,他实在是太灵活了。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product