Home  >  Article  >  Web Front-end  >  Recommend a jQuery plug-in template_jquery

Recommend a jQuery plug-in template_jquery

WBOY
WBOYOriginal
2016-05-16 16:21:26949browse

I have been using jQuery for quite some time, and I often write plugins for it. I've tried different ways to write it, and now this template is my favorite:

Copy code The code is as follows:

;(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);

//The following is the usage
$('div').borderize();
$('div').borderize({color: 'red'});

Here are the reasons why I like this template

1. You can still access the default options inside, even if it is overridden (simply accessed through the parent attribute)

 2. You can change the name of the plug-in by modifying the pluginName. (This method is also very beneficial for code compression)

Point #1 is very powerful. For example, if we want to override this method, but still want to keep the original method, we can look at the following example:

Copy code The code is as follows:
$('.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
});

Friends, you will also like this jQuery plug-in template, it is so flexible.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn