2010-06-18 48 views
0

给定以下插件如何设置所有实例的默认值?我希望它能像$ .datepicker.setDefaults()一样工作。jquery默认为插件的所有实例

(function($) { 
    $.fn.borderSwitcher = function(options) { 
     defaults = { 
      borderColor: 'Black', 
      borderWidth: '1px', 
      borderStyle: 'solid' 
     }; 

     return this.each(function() { 

      var settings = $.extend(defaults, options); 

      $(this).focus(function() { 
       //find a better way to set border properties 
       var props = settings.borderStyle + ' ' + settings.borderWidth + ' ' + settings.borderColor; 
       $(this).css('border', props); 
      }); 

      $(this).blur(function() { 
       $(this).css('border', ''); 
      }); 
     }); 
    }; 
})(jQuery); 
+0

按序使用默认值,U可以通过该空对象在如下面延伸 $ .extend({},缺省值,选项) ; – 2015-06-09 11:33:03

回答

1

在jQuery的添加他们对象iteself:

(function ($) { 
    $.borderSwitcher.defaults = { //NOTE: no fn here 
     borderColor: 'Black', 
     borderWidth: '1px', 
     borderStyle: 'solid' 
    }; 

    $.fn.borderSwitcher = function (options) { 
     var settings = $.extend($.borderSwitcher.defaults, options); 

     //the rest of your code 
    } 

}; 

//And outside your plugin definition, set the default for all new instances 
$.borderSwitcher.defaults.borderWidth = '2px'; 

$('.foo').borderSwitcher(); //with 2px 
$('.foo').borderSwitcher({borderWidth:'3px'}); //with 3px