jquery Plugin Writing Learning summary

Source: Internet
Author: User
Tags object object

The purpose of writing a plug-in is to encapsulate an existing set of methods or functions so that they can be reused elsewhere, facilitating later maintenance and improving development efficiency.

first, the type of plug-in
jquery's plugins are divided into 3 main types.
1. Plug-in for encapsulating object methods
2. Plug-in that encapsulates global functions
3. Selector plug-in
Here we mainly discuss the first kind of plug-in development process.
Plug-in for encapsulating object methods:
The plug-in is the most common kind of plug-in that encapsulates object methods to manipulate jquery objects obtained through selectors, and more than 95% of these plugins are plug-ins of this type.

second, the basic points of the plug-in
1. All object methods should be attached to JQUERY.FN, and all global functions should be attached to the jquery object itself.
2. Inside the plug-in, this refers to the jquery object currently fetched through the selector, not the DOM element.
3, all methods or function plug-ins, should end with a semicolon, in order to be more secure, and even add a semicolon to the head of the plug-in, so that their non-standard code to the plug-in impact.
4. Plug-ins should return a jquery object to ensure chained operation.
5, the use of closures.

third, the closure of the plug-in
Closures: Simply put, a closure is formed when an intrinsic function is called outside the outer function that contains them.
By using the characteristics of closures, it is possible to avoid internal temporary variables affecting the global space and continue to use $ as a jquery alias within the plug-in. Common jquery plugins are in this form:

;(function ($) {    //... })(jQuery);

And look at this code:

;(function ($) {    //定义一个局部变量foo,仅函数内部可以访问,外部无法访问    var foo;    varfunction(){        //...    }    //下面这句话相当于增加了一个jQuery对象上的全局函数BAR。可以通过$.BAR()的方式来访问内部定义的函数bar(),并且内部函数bar()也能访问foo    $.BAR = bar; })(jQuery);

In fact, this is similar to the one I wrote about modular programming, which used the closure concept, but in modular programming, the module method can be expanded by closures, and here is the method for adding $ objects, that is, the jquery global function plug-in.

Iv. jquery.extend () method
jquery provides two ways to extend the functionality of jquery, namely the JQuery.fn.extend method and the Jquery.extend () method. The former is used to extend the first of the three types of plug-ins mentioned earlier, which are used to extend the latter two plugins. Here is the Jquery.extend () method, in addition to the ability to extend the jquery object, there is a powerful feature that is used to extend an existing object object.

jQuery.extend(target,obj1,obj2,...objn);

Extends an object with one or more objects, and then returns the extended object.
Give me a chestnut:

varfalse5"foo" };vartrue"bar" };var newOptions = jQuery.extend(settings,options);

The result is:

newOptions = { validate: true,limit: 5,name: "bar" };

Obviously, the characteristics of this method can be easily used to override the default values in the input parameters, which are often used in the writing of the plugin.

v. Writing a jquery plug-in
in view of the previous internship (Mining Network e-commerce platform) to write a personal center column often encountered a variety of forms, in order to avoid duplication of work, thus learning to write a table with alternating color, Click on the plugin to select the color-changing feature.
Otherwise you need to repeat the following code every time:

$ ( "tbody>tr:odd" ). AddClass (  "odd" ); $ ( "Tbody>tr:even" ). AddClass ( "even" ); $ ( Span class= "hljs-string" > "Tbody>tr:has (: Checked)" ). AddClass ( "selected" ); $ ( "tbody>tr" ). Click ( function   ()  { var  hasselected = $ (this "). Hasclass ( "selected" ); $ (this ) [Hasselected? " Removeclass ": " AddClass "] (" selected "). Find (). Prop ( ' checked ' ,! hasselected);  

The

is not very functional, but it is also understood the specific development process of plug-ins.
First, we create a new file Jquery.tableBgColor.js, name the plug-in method Tablebgcolor, and then make a good frame:

;( function   ($)  { $.fn.extend ({ "t Ablebgcolor ": function                          { //set default  options= $.extend ({                         Odd: "odd" , Even: "even" ,                    Selected: "selected" },options); //... Plug-in code  return  this ; //return jquery object, guarantee chained Operation })}) (jQuery);  

Now, our goal should be to use a selector to select a table, after the Tablebgcolor () method is executed, the corresponding table of the TR element will be colored each row, and after clicking on a row will also change color, and select the corresponding checkbox within the row.
Therefore, simply modify the previously duplicated code into the framework:

;( function ($) {$.fn.extend ({"Tablebgcolor": function(options){                The //each () method iterates through the matching elements because there may be more than one element that matches                return  This. each ( function () {                    //Set default valuesOptions= $.extend ({odd:"Odd", even:"even", Selected:"Selected"},options); $("Tbody>tr:odd", This). addclass (options.odd); $("Tbody>tr:even", This). addclass (Options.even); $("Tbody>tr:has (: Checked)", This). AddClass ("Selected"); $("Tbody>tr", This). Click ( function () {                        varhasselected = $ ( This). Hasclass (options.selected); $( This) [hasselected?"Removeclass":"AddClass"] (options.selected). Find (': CheckBox '). Prop (' checked ',!hasselected);//Note this is prop, not attr.});return  This; })            }        });}) (JQuery);

At this point, the plugin is complete, now to test the plugin. Construct the table with ID test_table:

<table width="100%" style="table-layout: fixed" id="test_table">    //...此处省略</table>

Set the appropriate CSS class:

        Table{  text-align: left;             border-spacing: 0;         border-collapse: collapse; }        TD,th{  border: 1px solid #e2e2e2;         padding: 3px; }        th{  background-color: #1B6540;         color: #fff; }        . Odd{  background-color: #4FA46B; }        . Even{  background-color: #8ECE9F; }        . Selected{  background-color: #ecb6c4; }

Introducing plug-in Files:

<script src="jquery.min.js"></script><script src="jquery.tableBgColor.js"></script>

Call the plug-in method:

    $(function () {        $("#test_table").tableBgColor();    })

Get the following effect:

Click a line:

Check the function of the test operation:

$("#test_table").tableBgColor().find("th").css("background-color","red");

The head turns red:

It's done, perfect!
Now you may feel a little bit defective, the plugin does not write how to resolve the conflict (conflict) problem, it is not difficult to solve this problem, just change the previous code as follows:

;( function ($) {        varOld = $.fn.tablebgcolor;//First Save the previous method to be overwritten in old        //Note that a method for defining a plug-in is replaced so that the Tablebgcolor method can be called normally by the $.fn.tablebgcolor.noconflict later$.fn.tablebgcolor = function(options){                return  This. each ( function () {                    //Set default valuesOptions= $.extend ({odd:"Odd", even:"even", Selected:"Selected"},options); $("Tbody>tr:odd", This). addclass (options.odd); $("Tbody>tr:even", This). addclass (Options.even); $("Tbody>tr:has (: Checked)", This). AddClass ("Selected"); $("Tbody>tr", This). Click ( function () {                        varhasselected = $ ( This). Hasclass (options.selected); $( This) [hasselected?"Removeclass":"AddClass"] (options.selected). Find (': CheckBox '). Prop (' checked ',!hasselected); });return  This; })            }//define the Noconflict method of the Tablebgcolor object, so that the Tablebgcolor method is reverted to the method reserved in the previous old when this method is executed$.fn.tablebgcolor.noconflict = function(){$.fn.tablebgcolor = old;return  This; }}) (JQuery);

You may also feel a little bit of a flaw, the form is not able to do the full selection, of course, you can also write a full-featured plug-in, but it is important to note that the full selection of elements involved may be more, in the HTML structure of the design of the best with the function of the plug-in writing, here no more say.

jquery Plugin Writing Learning summary

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.