How to compile jquery plug-ins and jquery plug-ins

Source: Internet
Author: User
Tags rtrim jquery library

How to compile jquery plug-ins and jquery plug-ins

Previous

The purpose of writing a plug-in is to encapsulate a series of existing methods or functions so that they can be reused elsewhere, improving development efficiency and facilitating later maintenance. This article describes in detail how to compile the jQuery plug-in.

Type

JQuery plug-ins are mainly divided into three types

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. For example: the parent () method and appendTo () method. These methods are all built-in methods of jQuery. Usually, we can use it directly, just introduce the jQuery library.

2. encapsulate global functions

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

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.

Key Points

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. In the plug-in, this points to the jQuery object currently obtained through the selector. Unlike the general method, such as click, the internal this points to the DOM element.

4. You can use this. each to traverse all elements.

5. All methods or function plug-ins should end with a semicolon. Otherwise, problems may occur during compression. To ensure security, you can even add a semicolon to the plug-in header to avoid others' nonstandard Code affecting your plug-in code.

6. The plug-in should return a jQuery object to ensure the chained operation of the plug-in.

7. Avoid using $ as the alias of the jQuery object in the plug-in, instead of using the complete jQuery representation to avoid conflicts. Of course, you can also use the closure to avoid this problem, so that the plug-in continues to use $ as the jQuery alias.

Closure

Using the closure feature, you can avoid the impact of internal temporary variables on the global space, and you can continue to use $ as the jQuery alias in the plug-in content. Common jQuery plug-ins are in the following format:

(Function () {/* put the code here */})();

First define an anonymous function () {/* put code here */}, and then enclose it in parentheses to (function () {/* put code here */}) this form is finally executed using the () operator. Parameters can be passed for internal functions.

// For better compatibility, there is a semicolon before the start; (function ($) {// $ is used as the parameter of the anonymous function here/* put the code here, $ can be used as the abbreviation of jQuery */}) (jQuery); // here, jQuery is passed as a real parameter to the anonymous function.

The above code is a common jQuery plug-in Structure

Plug-in mechanism

JQuery provides two methods to expand jQuery functions, namely the jQuery. fn. extend () method and the jQuery. extend () method. The jQuery. fn. extend () method is used to expand the plug-ins that encapsulate object methods. The jQuery. extend () method is used to expand the plug-ins and Selector plug-ins that encapsulate global functions. Both methods accept a parameter of the Object type. The "name/value pair" of the Object represents "function or method name/function subject" respectively"

[JQuery. fn. extend ()]

The jQuery. fn. extend () method is used to combine the content of an object into a jQuery prototype to provide a new jQuery instance method.

<Label> <input type = "checkbox" name = "foo"> Foo </label> <input type = "checkbox" name = "bar"> Bar </ label> <button id = "btn1"> select all </button> <button id = "btn2"> none </button> <script> jQuery. fn. extend ({check: function () {return this. each (function () {this. checked = true ;}) ;}, uncheck: function () {return this. each (function () {this. checked = false ;}) ;}}); $ ('# btn1 '). click (function () {$ ("input [type = 'checkbox']"). check () ;}); $ ('# btn2 '). click (function () {$ ("input [type = 'checkbox']"). uncheck () ;}); </script>

[JQuery. extend ()]

The jQuery. extend () method extends an object with one or more other objects, and then returns the extended object.

jQuery.extend( target [, object1 ] [, objectN ] )

For example, merge the settings object and options object, modify and return the settings object.

Var settings = {validate: false, limit: 5, name: "foo"}; var options = {validate: true, name: "bar"}; var newOptions = jQuery. extend (settings, options); console. log (newOptions); // Object {validate: true, limit: 5, name: "bar"} jQuery. the extend () method is often used to set a series of default function foo (options) {options = jQuery. extend ({name: "bar", length: 5, dataType: "xml"}, options );}

If the user sets the corresponding value in the options object of the passed parameter when calling the foo () method, the set value is used; otherwise, the default value is used.

By using the jQuery. extend () method, you can easily overwrite the default value with input parameters. At this time, the call to the method is still consistent, but the input is a ing instead of a parameter list. This mechanism is more flexible and concise than the traditional method of detecting each parameter. In addition, the use of named parameters means that adding new options will not affect the code written in the past, so that developers can use it more intuitively and clearly.

Compile plug-ins

1. Plug-ins that encapsulate jQuery object Methods

Compile the color () Plug-in for setting and obtaining colors. This plug-in is used to implement the following two functions:

(1) set the color of the Matching Element

(2) obtain the color of the matched element (the first in the element set)

Because it is a method extension for jQuery objects, jQuery is used to expand the first type of plug-ins. fn. extend () is written. Here we provide a parameter value for this method. If the parameter value is passed when the method is called, the font color is set using this parameter, otherwise, the font color value of the matching element is obtained.

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

In fact, the content of the CSS () method has a mechanism to determine whether the value is undefined. Therefore, different values can be returned based on different passing parameters. Therefore, the code can be deleted as follows:

;(function(){  jQuery.fn.extend({    "color":function(value){      return this.css("color",value);       }         }); })(jQuery);
<Span id = "test"> test text </span> <input type = "color" id = "color"> <script>; (function ($) {$. fn. extend ({"color": function (value) {return this.css ("color", value) ;}}) ;}( jQuery) ;$ ('# color '). on ('change', function () {$ ('# test '). color ($ (this ). val () ;}) </script>

In addition, if you want to define a set of plug-ins, you can use the following code:

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

2. Plug-ins that encapsulate global functions

This type of plug-in adds a function in the jQuery namespace.

For example, two new functions are added to remove spaces on the left and right. Although jQuery already provides the jQuery. trim () method to remove spaces at both ends, in some cases, you only want to remove spaces at one side.

The functions that remove spaces on the left and right are written as the following jQuery code. (Text | "") is used to prevent the passed text string variable from being in an undeined special State. If the text is undeined, the string "" is returned; otherwise, the string text is returned. This is to ensure that the next string replacement method replace () method will not go wrong

;(function($){  $.extend({   ltrim:function( text ){      return (text || "").replace(/^\s+/g,"");    },    rtrim:function(   text ){        return (text || "").replace(/\s+$/g,"");    }  }); })(jQuery);var $str = "  test  ";console.log($.trim($str));//'test'console.log($.ltrim($str));//'test  'console.log($.rtrim($str));//'  test'

3. Custom Selector

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, determine whether to retain the element based on whether the return value of this selection function is true or false, so that the matching element node 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 indicates 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 ".

There are already lt, gt, and eq selectors in jQuery, so here we write a selector between the two ()

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.

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

[Note] after testing, the value of the second parameter I in the function is always 0, and the index value cannot be obtained. In this case, you need to create an index by yourself. The Code is as follows:

;(function($){  var $index = -1;  $.extend($.expr[":"],{    between:function(a,i,m){      var temp=m[3].split(",");        $index++;         return +temp[0]<$index&&$index<+temp[1];    }  });})(jQuery);
<Div> <I> 0 </I> <I> 1 </I> <I> 2 </I> <I> 3 </I> <I> 4 </I> <I> 5 </I> </div> <button id = "btn"> test </button> <script>; (function ($) {var $ index =-1; $. extend ($. expr [":"], {between: function (a, I, m) {var temp = m [3]. split (","); $ index ++; return + temp [0] <$ index & $ index <+ temp [1] ;}});}) (jQuery); $ ('# btn '). click (function () {$ ('I: between(1, 5 '''background .css ('background', 'lightblue') ;}); </script>

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

Related Article

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.