What is a jquery plugin? Common jquery plugins are divided into three types: plug-ins that encapsulate object methods, plug-ins that encapsulate global functions, and selector plug-ins. What about the writing and use of each jquery plugin based on the three jquery plugins? Let's talk about the use and notation of jquery plugins.
jquery Plugin Categories:
1. Plug-in for encapsulating object methods
This plug-in is the most common plug-in that encapsulates object methods and is used to manipulate jquery objects obtained through selectors.
2. Plug-ins that encapsulate global functions
You can add separate functions to the jquery namespace. For example, the Jquery.noconflict () method, the commonly used Jquery.ajax () method, and the Jquery.trim () method for removing the first space are all plugins attached to the kernel as global functions within jquery.
3. Selector Plug-in
In some cases, a selector plug-in is required.
Basic points of the plugin
The file name of the 1.jQuery plugin is named jquery. [plugin name].js to avoid confusion with other JavaScript library plugins.]
2. All object methods should be attached to the Jquery.fn object, and all global functions should be attached to the jquery object itself.
3. Inside the plug-in, this refers to the jquery object currently fetched through the selector, rather than the DOM element inside this, as in the general method, such as the Click () method.
4. All elements can be traversed by This.each.
5. All methods or function plug-ins should end with a semicolon, or the problem may occur when compressing. To be more secure, you can even add a semicolon to the plugin's head to prevent other people's nonstandard code from affecting the plugin.
6. The plugin should return a jquery object to ensure that the plug-in can be chained. Unless the plug-in needs to return some amount that needs to be fetched, such as a string or an array.
7. Avoid using $ as an alias for jquery objects inside the plug-in, instead use the full jquery to represent it. This avoids conflicts and, of course, you can use closures as a technique to circumvent this problem, allowing the plugin to continue using $ as an alias for jquery. Many plugins do this.
Closures in plugins
With regard to closures, ECMAScript a simple description: Allows the use of intrinsic functions (that is, function definitions and function expressions in another function body), and these intrinsics can access all local variables, arguments, and other intrinsics declared in the outer function where they are located. When one of these intrinsics is called outside the outer function that contains them, a closure is formed. That is, the intrinsic function is executed after the external function returns. When this inner function executes, it must still access local variables, arguments, and other intrinsic functions of its external function. The values for these local variables, parameters, and function declarations (initially) are the values that are returned by the external function, but you also receive the effect of the intrinsic function.
First define an anonymous function () {/* Here to place the code */}, and then enclose it in parentheses into (function () {/* Place code */}) This form, and finally through () this operator to execute. Parameters can be passed in for use by internal functions.
Note For better compatibility, there is a semicolon before you begin:
;(function ($) {//start with the $ as the formal parameter for the anonymous function/* Here, you can use $ as the abbreviated alias for jquery */}) (jquery); This is where jquery is passed as an argument to an anonymous function.
The above is the structure of a common jquery plugin.
The mechanism of the jquery plugin
jquery provides two methods for extending the functionality of jquery, the JQuery.fn.extend () method and the Jquery.extend () method. The former is used for the 1th of the 3 plug-in types mentioned earlier, which is used to extend the latter two plugins. Both methods accept a parameter, which is of type object. The "name/value pairs" of the object objects represent "function or method name/function Body", respectively.
The Jquery.extend () method, in addition to being used to extend the jquery object, has a powerful function of extending an existing object object.
The jquery code is as follows:
Jquery.extend (Target,obj1,....... [OBJN]) extends an object with one or more other objects, and then returns the extended object. For example, merging Settings objects and options objects, modifying and returning settings objects. var settings={validate:false,limit:5,name: "foo"}; var options={validate:true,name: "Bar"}; var newoptions= Jquery.extend (settings,options);
The result is:
Newoptins={valitdate:true,limit:5,name: "Bar"};
The Jquery.extend () method is often used to set a series of default parameters for a plug-in method, as shown in the following code:
function foo (options) {options=jquery.extend ({name: "Bar", Limit:5, DataType: "xml"},options);
If the Foo () method is called and the corresponding value is set in the passed parameter options object, the set value is used, otherwise the default value is used. The code is as follows:
Foo ({name: "A", Length: "4", DataType: "JSON"}); Foo ({name: "A", Length: "4"}); Foo ({name: "a"}); Foo ();
By using the Jquery.extend () method, it is convenient to override the default value with the passed-in parameters. At this point, the call to the method remains consistent, except that a map is passed in instead of a parameter list. This mechanism is not only flexible but also more concise than the traditional way to detect each parameter. Also, using named parameters means that adding new options will not affect the code that was written in the past, making the developer more intuitive to use.
Writing jquery Plugins
1. Plug-ins that encapsulate jquery object methods
Write a plug-in that sets get colors
First describes how to write a color () plug-in. The plugin is used to implement the following two functions.
(1) Sets the color of the matching element.
(2) Gets the color of the matching element (1th in the element collection).
First, the plug-in is named Jquery.color.js by specification.
And then put a good frame in the JavaScript file. Because it is a method extension to a jquery object, it is written using the 1th class method JQuery.fn.extend ().
;(function ($) {$.fn.extend ({"Color": function (value) {//write plug-in code here}});}) (JQuery);
This method is provided with a parameter value, if the method is called when the value of the parameter is passed, then the value is used to set the font color; otherwise, it is the value of the font color of the matching element.
First, implement the 1th function, set the font color. Note that because this inside the plug-in refers to a jquery object, not a normal DOM object. The code is as follows:
;(function ($) {$.fn.extend ({"Color": function (value) {return this.css ("Color", value);});}) (JQuery);
Next, implement the 2nd function. If you do not pass a parameter to a method, you get the value of the color of the 1th object in the collection object. Because the CSS () method itself has the ability to return a 1th matching element style value, there is no need to get the 1th element through EQ (). As long as these two methods are combined, determine if value is undefined.
The jquery code is as follows:
;(function ($) {$.fn.extend ({"Color": function (value) {if (color===undefined) {return this.css ("Color", value);} else{Return this.css ("Color", value);}} }); }) (JQuery);
As a result, the plugin is complete. Now let's test the code.
<script type= "Text/javascript" >//Plug-in writing;(function ($) {$.fn.extend ({"Color": function (value) {if (color=== Undefined) {return this.css ("Color", value);} else{Return this.css ("Color", value);}} }); }) (jQuery); Plug-in App $ (function () {//) view the color style value of the first Div, alert ($ ("div"). Color () + "\ n Returns a string that proves that the plugin is available. ”); Set all the div font colors to Red alert ($ ("div"). Color ("red") + "\ n Returns the object proof that you got the jquery objects. ");}) </script> <div style=" color:red ">red</div> <div style=" Color:blue ">blue</div> <div style= "Color:green" >green</div> <div style= "Color:yellow" >yellow</div> in addition, If you are defining a set of plugins, you can use the following notation::(function ($) {$.fn.extend ({"Color": function (value) {//Plug-in code}, "Border": function (value) {// Plugin code}, "Background": function (value) {//Plugin code}}; }) (JQuery);
Table interlaced plug-in
The code for the table interlaced color is as follows:
$ ("tbody>tr:odd"). AddClass ("odd"); $ ("Tbody>tr:even"). AddClass ("even"); $ (' tbody>tr '). Click (function () {///To determine if Var hasselected=$ (this) is selected. Hasclass (' selected ');//If selected, remove the selected class, Otherwise, add the selected class $ (this) [hasselected?] Removeclass ":" AddClass "] (' selected ')//Find the Internal checkbox, set the corresponding property. Find (' checkbox '). attr (' checked '). hasselected); }); If the check box is selected by default, the high color is $ (' Tbody>tr:has (: Checked) '). AddClass (' selected ');
First, the plug-in method named Alterbgcolor, and then a good framework for the plug-in method, the jquery code is as follows:
;(function ($) {$.fn.extend ({"Alterbgcolor": function (Options) {//Plugin Code}}) (JQuery);
Once the framework is complete, the next step is to define default values for the options. The default build is this ({odd: "odd", even: "Even", Selected: "Selected"}) an object. This can be done through $ ("#sometable"). Alterbgcolor ({odd: "odd", even: "Even", Selected: "Selected"}) to customize the style class name of the parity row and the selected style class name. Also, use the $ ("#sometable") directly. Alterbgcolor () to apply the default style class name.
The jquery code is as follows:
;(function ($) {$.fn.extend ({"Alterbgcolor": function (Options) {options=$.extend ({odd: "odd",/* even line style */even: "even",/ * Odd Line Style */selected: "Selected"/* Select row style */},options); } }); }) (JQuery);
If you need to use the properties of the options object in later programs, you can use the following methods to obtain:
options.odd; Gets the value of the odd property in the Options object Options.even; Gets the value of the even property in the Options object options.selected; Gets the value of the selected property in the Options object
The next step is to put these values in the program instead of the fixed values in the previous program.
Finally, there is the problem of matching elements. Obviously you cannot select a table row directly with $ (' tbody>tr '), which will cause all <tr> elements in the page to be discolored. You should use the selector to select a table, and after performing the Alterbgcolor () method, the corresponding table <tr> elements are interlaced. Therefore, all objects selected through $ (' tbody>tr ') will need to be rewritten into $ (' tbody>tr ', this), which represents the lookup within the matching element (within the current table) and applies the default values in the previous step. The jquery code is as follows:
;(function ($) {$.fn.extend ({"Alterbgcolor": function (Options) {//Set default value Options=$.extend ({odd. ") Odd ", even." Even ", selected:" Selected "},options); $ ("tbody>tr:odd", this). addclass (options,odd); $ ("Tbody>tr:even", this). addclass (Options,even); $ ("Tbody>tr", this). Click (function () {///To determine if Var hasselected=$ (this) is selected. Hasclass (options,selected);//If selected, Remove the selected class, otherwise add the selected class $ (this) [hasselected? Removeclass ":" AddClass "] (options,selected)//Find internal checkbox, set corresponding property. Find (': CheckBox '). attr (' checked ',!hasselected ); }); If the Radio box is selected by default, the high color is $ (' Tbody>tr:has (: CHECKD), this '). addclass (options,selected); Rerturn this; Returns this to make the method chain}}); }) (JQuery);
At the end of the code, return this and let the plugin be chained.
At this point, the plugin is complete. Now to test this plugin. Construct two tables with IDs table1 and table2, and then use one of the <table> call the Alterbgcolor () method to see if they work independently and have a chain of ability.
The jquery code is as follows:
$ (' #table2 '). Alterbgcolor ()//Application plugin. Find ("th"). CSS ("Color", "red"); Chain-operated
It is important to note that jquery's selectors may match 1 or more elements. Therefore, these conditions must be taken into account when writing plug-ins. You can call the each () method inside the plug-in to traverse the matching element and then execute the appropriate method, which in turn references each DOM element. The following jquery code shows:
;(function ($)) {$.fn.extend ({"Someplugin": function (Options) {return This.each (function () {//Place Code})})}) (JQuery);