jquery----> How to Create a Basic Plugin (translation)

Source: Internet
Author: User

http://learn.jquery.com/plugins/basic-plugin-creation/

How to create a basic plug-in

Sometimes you want to provide some functionality throughout the code. For example, perhaps you want a single method, you can call a jquery selection to perform a series of operations on selection. In this case, you may need to write a plug-in.

How jquery works 101: JQuery Object method

Before we write our own plugins, we must first understand how jquery works. Look at this code:

1 $ ("a"). CSS ("Color", "red");

Here are some very basic jquery codes, but do you know what's going on behind the scenes? Whenever you use the $ function to select an element, it returns a JQuery object. This object contains all of the methods you use (. css (),. Click (), and so on) and all the elements that are appropriate for your selector. The jquery object gets these methods from the $. Fn object. This object contains all the JQuery object methods, and if we want to write our own method, it also needs to include these methods.

Basic Plugin Authoring

Suppose we want to create a plug-in that makes the text in a set of retrieved elements appear green. All we have to do is add a function named Greenify to the $. FN, and it will be as available as any other jquery object method.

1 function () {2     this. css ("Color", "green" ); 3 }; 4  5 // makes all the links green.
6 //Make all the links turn green

Note that to use another method. css (), we use this instead of $ (this). This is because our greenify function is part of the same object as the. css ().

Link

This works, but we need to do something for our plugins to survive in the real world. When you link five or six actions to a selector, one of the features of jquery is the link. This is done by having all the JQuery object methods return the original jquery object again (with some exceptions: call. Width () and return the width of the selected element without a parameter, and it is not linked). To make our plug-in method chaining requires a line of code:

1 function () {2     this. css ("Color", "green" ); 3     return  This ; 4 }5  6 $ ("a"). Greenify (). addclass ("greenified");

Protect $ aliases and add scopes

The

$ variable is very popular in the JavaScript library, and if you use another library of jquery, you must make jquery do not use $ with jquery.noconflict (). However, this will corrupt our plugin because it was written in the case that $ is an alias of the jquery function. In order to work with other plugins and still use the jquery $ alias, we need to put all the code in the function expression that is called immediately, then pass the function jquery and name the parameter $:

1 (function  ($) {2  3     function() {4 This         . CSS ("Color", "green" ); 5         return  This ; 6     }; 7  8 } (JQuery));

In addition, the primary purpose of calling functions immediately is to allow us to have our own private variables. Suppose we want a different green, we want to store it in a variable.

  1  (function   ($) {  2   3
     var  shade = "#556b2f" ;   4   5  $.fn.greenify = function   () {  6  this . CSS (" color "  7  return  th is  ;   8  };   9  10 } (JQuery)); 

Minimized plug-in encapsulation

Writing a plug-in takes only $. One slot in the FN is a good practice. This reduces the chance that the plugin will be overwritten, and also reduces the opportunity for the plugin to overwrite other plugins. In other words, this is bad:

1(function( $ ) {2  3$.fn.openpopup =function() {4         //Open popup code.5     };6  7$.fn.closepopup =function() {8         //Close popup code.9     };Ten   One} (JQuery));

It is better to have a slot and use parameters to control the operations performed by one slot.

1(function( $ ) {2  3$.fn.popup =function(action) {4  5         if(Action = = = "Open") {6             //Open popup code.7         }8  9         if(Action = = = "Close" ) {Ten             //Close popup code. One         } A   -     }; -   the} (JQuery));

Use the each () method

A typical jquery object will contain references to any number of DOM elements, which is why jquery objects are often referred to as collections. If you want to do anything about a particular element (such as getting data properties, calculating a specific location), you need to use. each () to iterate through the elements.

1 function () {2  3     return this. All (function() {4         // do something to each element here.  Here are some things to do for each element.  5    }); 6  7 };

Note that we return the result of. each () instead of returning the this result. Since. each () is already linked, it returns this, and then we return. This is a better way to sustain sustainability than we have done so far.

Accept Options

As your plugins become more complex, it's a good idea to make your plugin customizable by accepting the option. The simplest approach is to use object literals, especially if there are many options. Let's change our green plugin to accept some options.

1(function ( $ ) {2  3$.fn.greenify =function(options) {4  5         //The the easiest way to has the default options.//This is the simplest method with the defaults. 6         varSettings =$.extend ({7             //these is the defaults.//These are the default settings. 8Color: "#556b2f",9BackgroundColor: "White"Ten }, options); One   A         //Greenify The collection based on the settings variable.//Make the collection green according to the set variable.  -         return  This. css ({ - Color:settings.color, the BackgroundColor:settings.backgroundColor -         }); -   -     }; +   -} (JQuery));

Example:

1 $ ("div" ). Greenify ({2     color: "Orange"3 });

The #556b2f color default value is covered by $. Extend () in orange.

Put it together.

Here is an example of a small plugin that uses some of the techniques we've discussed:

1(function( $ ) {2  3$.fn.showlinklocation =function() {4  5          This. Filter ("a"). each (function() {6             varlink = $ ( This );7Link.append ("(" + link.attr ("href") + ")" );8         });9  Ten         return  This; One   A     }; -   - } (JQuery)); the   - //Usage Example: -$ ("a"). Showlinklocation ();

This handy plugin iterates through all the anchors in the collection and appends the href attribute to the parentheses.

1 <!--before plugin is called: -2 <ahref= "page.html">Foo</a>3  4 <!--After plugin is called: -5 <ahref= "page.html">Foo (page.html)</a>

Our plugins can be optimized, but:

1(function( $ ) {2  3$.fn.showlinklocation =function() {4  5          This. Filter ("a"). Append (function() {6             return" (" + This. href + ")";7         });8  9         return  This;Ten   One     }; A   -} (JQuery));

We use the function of the. Append () method to accept the callback, and the return value of the callback determines the additional content of each element in the collection. Also note that we did not use the. attr () method to retrieve the href attribute because the local DOM API gives us easy access to the HREF attribute with the appropriate name.

jquery----> How to Create a Basic Plugin (translation)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.