Create a simple jquery plugin
1. General methods for creating basic plug-ins:
$.fn.greenify = function() { this.css( "color", "green" );}; $( "a" ).greenify();2. Add a chained call: add the return value of this in the preceding method.
$.fn.greenify = function() { this.css( "color", "green" ); return this;} $( "a" ).greenify().addClass( "greenified" );3. Protect the js namespace clean and reduce the pollution of other plug-ins to avoid conflicts with other plug-ins. We need to put our code in a function expression that is called immediately.
Then pass jQuery and name the parameter $
(function ( $ ) { $.fn.greenify = function() { this.css( "color", "green" ); return this; }; }( jQuery ));In addition, the main purpose of calling a function immediately is to allow us to use our private variables and store the values in a variable.
In this way, private variables can be defined in the call function immediately without polluting the public environment.
(function ( $ ) { var shade = "#556b2f"; $.fn.greenify = function() { this.css( "color", shade ); return this; }; }( jQuery ));Define as much as possible in a method
(function( $ ) { $.fn.openPopup = function() { // Open popup code. }; $.fn.closePopup = function() { // Close popup code. }; }( jQuery ));
It should be changed:
(function( $ ) { $.fn.popup = function( action ) { if ( action === "open") { // Open popup code. } if ( action === "close" ) { // Close popup code. } }; }( jQuery ));
4. If you get a dom set, you want to use the qualified elements. the method of each () loops through this dom set, and returns the modified element set for the Operation to continue calling the method.
$.fn.myNewPlugin = function() {
return this.each(function() { // Do something to each element here. }); };
5. Extended parameters: use custom parameters to overwrite the default parameters $. extend (settings, options );
function ( $ ) { $.fn.greenify = function( options ) { // This is the easiest way to have default options. var settings = $.extend({ // These are the defaults. color: "#556b2f", backgroundColor: "white" }, options ); // Greenify the collection based on the settings variable. return this.css({ color: settings.color, backgroundColor: settings.backgroundColor }); }; }( jQuery ));
$( "div" ).greenify({ color: "orange"});The following is a comprehensive example:
<Script type = "text/javascript" src = "js/jquery-1.11.1.js"> </script> <script type = "text/javascript"> (function ($) {$. fn. greenify = function (options) {var settings = $. extend ({color: "green", backgroundColor: "black"}, options); var that = this; return that.each(function({{{}(this}.css ({color: settings. color, backgroundColor: settings. backgroundColor}) ;};};} (jQuery) ;$ (function () {$ ("a: lt (2 )"). greenify ({color: "orange" 00000000.html (111) ;}); </script> This is my HTML page.
Dianji dianji11 dianji221