Use and writing of the plug-in "sharp jQuery", and writing of the jquery plug-in

Source: Internet
Author: User

Use and writing of the plug-in "sharp jQuery", and writing of the jquery plug-in
Types of jQuery plug-ins

1. encapsulate object Methods
This plug-in encapsulates object methods and is used to operate jQuery objects obtained by selector. It is the most common plug-in. This type of plug-in can take advantage of the powerful advantages of the jQuery selector. A considerable number of jQuery methods are "inserted" in the kernel in the jQuery script library in this form, such as parent () method, appendTo () method, and so on.

2. encapsulate global functions
You can add independent functions to the jQuery namespace. For example, the commonly used jQuery. ajax () method and jQuery. trim () method with spaces at the beginning and end are all attached to the kernel as the global function plug-in.

3. selector plug-in
Although jQuery's selector is very powerful, in a few cases, you still need to use the selector plug-in to expand some of your favorite selectors.

JQuery plug-in mechanism

The mechanism of jQuery plug-in is very simple. It is to use jQuery. fn. extend () and jQuery. extend () methods provided by jQuery to extend jQuery's functions.

JQuery. fn. extend () is mostly used to extend the first of the three types mentioned above. jQuery. extend () is used to extend the last two types of plug-ins. Both methods accept a parameter of the Object type. The "name/value pair" of the Object represents the "function or method name/function subject ".

Compile some Tips of the jQuery plug-in

1. The file name of the jQuery plug-in is recommended to be jquery. [plug-in name]. js to avoid confusion with other JS library plug-ins.
2. All object methods should be appended to the jQuery. fn object, and all global functions should be appended to the jQuery object itself.
3. Add a semicolon to the plug-in header to avoid the impact of others' nonstandard code on the plug-in.
4. All methods or function plug-ins should end with a semicolon to avoid problems during compression.
5. Unless the plug-in needs to return some variables to be obtained, the plug-in should return a jQuery object to ensure that the plug-in can be chained.
6. The jQuery. extend () method is used to set the default parameters of the plug-in method to increase the availability of the plug-in.

JQuery plug-in Structure

The jQuery plug-in structure is as follows:

; (Function ($) {/* put the plug-in code here. You can use $ as the alias of jQuery */}) (jQuery );
Practice of encapsulating jQuery object method plug-in

Case 1:

Function: sets the color of the selected element to obtain the color of the first selected element.
Name: jquery. color. js

; (Function ($) {$. fn. extend ({// write the plug-in code here});}) (jQuery );

Idea: Set a parameter value. If the parameter value is passed during the call, the color is set; otherwise, the color is obtained. You can use the css method provided by jQuery to obtain and set colors.

;(function($){     $.fn.extend({         "color":function(value){             if(value==undefined){                 return this.css("color");             }             else{                 return this.css("color",value);             }         }     }); })(jQuery); 

Because css() has the first element when obtaining the color, you can directly use this.css ("color") here.

If it is a group of plug-ins, you can use the following code:

; (Function ($) {$. fn. extend ({"color": function (value) {// plug-in code}, "border": function (value) {// plug-in code}, "background ": function (value) {// plug-in code}) ;}( jQuery );

Case 2: Write the table barrier coloring plug-in

; (Function ($) {$. fn. extend ({"alterBgColor": function (options) {// set the default value option = $. extend ({odd: "odd", even: "even", selected: "selected"}, options); // note that the options is the same as the function (options) above) the option in is the same object // the color of the line $ ("tbody> tr: enev", this ). addClass (option. even); $ ("tbody> tr: odd", this ). addClass (option. odd); // click the row color change $ ('tbody> tr', this ). click (function () {var hasSelected = $ (this ). hasClass (option. selected); $ (this )[ HasSelected? "RemoveClass": "addClass"] (option. selected). find (": checkbox"). attr ('checked ',! HasSelected) ;}); $ ("tbody> tr: has (: checked)", this ). addClass (option. selected); return this; // return this so that the method can be chained}) ;}( jQuery );
Call method:
$("#table2").alterBgColor().find("th").css("font-size","18");
Encapsulation of global function plug-ins

Function: Remove spaces on the left or right separately.
Name: jquery. lrtrim. js

Structure:

; (Function ($) {$. extend ({ltrim: function (text) {// plug-in code}, rtrim: function (text) {// plug-in code});}) (jQuery );

Idea: This type of plug-in adds a function in the jQuery namespace and uses a regular expression directly.
Complete code:

;(function($){     $.extend({         ltrim:function(text){             return (text||"").replace(/^\s+/g,"");         },         rtrim:function(text){             return (text||"").replace(/\s+$/g,"");         }     }); })(jQuery); 
User-Defined selector plug-in practice

JQuery is famous for its powerful selector. What is the working principle of jQuery's selector?

JQuery's selection parser first uses a set of regular expressions to parse the selector, and then executes a function for each selected character parsed, which is called the selection function. Finally, whether to retain the element is determined based on whether the return value of this selection function is true or false, so that Matching Element nodes can be found.

For example, $ ("div: gl (1)"), the selector first obtains all <div> elements and then implicitly traverses these <div> elements, the <div> elements are passed to the selector function corresponding to the gt component together with the parameters such as "1" in the brackets for determination. If true is returned, it is retained; otherwise, it is not retained. The result is a set of <div> elements that meet the requirements.

The selector function accepts three parameters in the following format:

function (a,i,m){     //... } 

The first parameter is a, which refers to the DOM element currently traversed.
The second parameter is I, which refers to the index value of the DOM element currently traversed, starting from 0.
The third parameter is m, which is a product after further parsing by the jQuery Regular Expression parsing engine. It is an array: The most important one is m [3], at $ ("div: gl (1) ") is the number" 1 "in the brackets ".


The lt, gt, and eq selectors are already available in jQuery, so here we write a selector between them (.
Function: select an element with an index value between a and B (a <B, a, and B are positive integers ).
Name: jquery. between. js
Structure:

; (Function ($) {$. extend ($. expr [":"], {between: function (a, I, m) {// plug-in code}) ;}( jQuery );

Idea: in the preceding three parameters, m [3] is in the form of "a, B". Therefore, m [3] is separated, then compare it with the index value I. If I is in the range indicated by m [3], true is returned; otherwise, false is returned.
Complete code:

;(function($){     $.extend($.expr[":"],{         between:function(a,i,m){             var temp=m[3].split(",");             return +temp[0]<i&&i<+temp[1];         }     }); })(jQuery); 

Note: + temp [0] and + temp [1] are used to convert a string-type number into a number.

For more information, see what? You won't write JQuery plug-in yet

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.