This article mainly recommends a jQuery plug-in template, which is my favorite. The reason is simple, easy to use, and more optional. For more information, see jQuery. I have been using jQuery for a long time, and I will often write some plug-ins for it (plugin ). I tried to write in different ways. now this template is my favorite one:
The code is as follows:
; (Function ($ ){
// Multiple plugins can go here
(Function (pluginName ){
Var defaults = {
Color: 'black ',
TestFor: function (p ){
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 );
// Usage
$ ('P'). borderize ();
$ ('P'). borderize ({color: 'red '});
The following are the reasons why I like this template:
1. you can still access the default options, even if it is overwritten (simply access through the parent attribute)
2. modify pluginName to change the plug-in name. (This method is also very beneficial to code compression)
Point #1 is very powerful. for example, we want to repeat this method, but we still want to retain the original method. let's look at the example below:
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. ULTS ults. color
});
Friends, you will also like this jQuery plug-in template, which is too flexible.