jquery Plugin Development Tutorials

Source: Internet
Author: User

jquery Plugin Development Tutorials

--Raise your level of jquery to a step

The most successful part of jquery, I think, is that its extensibility has attracted many developers to develop plug-ins to build an ecosystem. This is like the big companies competing to do the platform, the platform to the world. Apple, Microsoft, Google and other giants, have their own platform and ecological circle.

Learning to use jquery is not difficult, because it's easy to learn, and I'm sure you'll be using or familiar with many of its plugins after you touch jquery. If you want to upgrade your ability to a step, it's a good idea to write a plugin that belongs to you.

This tutorial may not be the most elaborate, but it must be the most detailed.

jquery Plugin Development model

The software development process needs certain design pattern to guide the development, has the pattern we can better organize our code, and from these predecessors summed up the pattern to learn many good development experience.

According to the description in jquery advanced programming, there are three main ways of developing jquery plugins:

1. Expand jquery with $.extend ()

2. Add new methods to jquery via $.fn

3, by $.widget () application of the jquery UI parts factory method to create

Usually we use the second method for simple plug-in development, saying that simplicity is relative to the third way. The third way is to develop more advanced jquery parts, the model developed by the parts with a lot of jquery built-in features, such as the plug-in state information auto-save, a variety of plug-ins commonly used methods, very intimate, here is not elaborate.

And the first is too simple, just in the jquery namespace or in the sense of adding a static method to jquery. So we call through the $.extend () Add function directly through the $ symbol call ($.myfunction ()), without having to check the DOM element ($ (' #example '). MyFunction ()). Take a look at the example below.

First prepare <script type= "Text/javascript" src= "Jquery.js" ></script> in HTML, you can download the latest version on the jquery website.

Create new plug.html files and plug.js, and reference them in HTML;

As follows:

<! DOCTYPE html><p></p>
</body>

Write JS in plug.js:

$.extend ({    sayhello:function (name) {         $ (' P '). html (' Hello, ' + (name?name: ' dute ') + '! ');        Console.log (' Hello, ' + (name?name: ' dute ') + '! ');}    });

Then reference him in HTML and add the following lines of code to the body:

<script type= "Text/javascript" >    $.sayhello ();     $.sayhello (' Lucy '); </script>     

Operation Result:

The text page displays with parameters because the default is overridden.

In the above code, a SayHello function is added to jquery via $.extend () and then called directly via $. Here you can think that we have completed a simple jquery plugin.

But as you can see, it is convenient to define some auxiliary methods in this way. A custom console, for example, outputs information in a specific format that can be called once in a program by jquery wherever it is needed.

Look at the following example:

$.extend ({    logg:function (message) {        var now = new Date (),        y=now.getfullyear (),        m=now.getmonth () +1,        d=now.getdate (),        h=now.gethours (),        mins=now.getminutes (),        s=now.getseconds (),        time=y + '/' + M + '/' + D + ' + H + ': ' + mins + ': ' + S;        Console.log (time+ ' by  : ' +message);        $ (' P '). html (time+ ' by  : ' +message);    }});

Call mode: $.logg (' Ethancoco ');

Operation Result:

But this approach does not take advantage of the convenience of jquery's powerful selectors, the need to work with DOM elements and to better apply the plug-in to selected elements, or to use the second development approach.

Most of the plugins you see or use are developed in this way.

First look at its basic format:

$.fn.pluginname = function () {

Your code goes here

}

Basically is to $.fn above add a method, name is our plug-in name. Then our plug-in code expands in this method.

For example, if we turn all the link colors on the page to red, we can write the plugin as follows:

$.fn.myplugin = function () {

In this case, this refers to the element selected with jquery.

Example: $ (' a '), then this=$ (' a ')

This.css (' Color ', ' red ');

}

Within this function of the plug-in name definition, this refers to the element that we select with the jquery selector when invoking the plugin, which is generally a collection of jquery types. For example, $ (' a ') returns a collection of all a tags on the page, and the collection is already a jquery wrapper type, which means that you can call it directly when you manipulate it.

Other methods of jquery without the need for a dollar sign to wrap.

So in the plugin code above, we invoke the jquery CSS () method on this, which is equivalent to calling $ (' a '). css ().

It is important to understand the meaning of this in this place. So that you know why you can call the jquery method directly at the same time as elsewhere this means that we need to re-wrap with jquery in order to invoke, as described below. Beginner is easy to be dizzy by the value of this, but it is not difficult to understand.

Now you can go to the page to try our code, put a few links on the page, call the plugin after the link font into red.

Add the following code to the body:

<ul id= "Ulp" >        <li>            <a href= "http://www.qq.com/" >Tencent</a>        </li>        <li>            <a href= "http://souhu.com/" >Souhu</a>        </li>        <li>            <a href= " http://taobao.com/">Taobao</a>        </li></ul><p>i am label p, I am fine! I am not a like label a!</p>

Call Mode:

$ (function () {        $ (' a '). Myplugin ();    });

Operation Result:

Further, each specific element is processed in the plug-in code instead of a collection, so that we can operate on each element accordingly.

We already know that this refers to the collection returned by the jquery selector, so each element of the collection can be processed by invoking the. each () method of jquery, but it is important to note that within each method, this refers to the normal DOM element. If you need to invoke the JQuery method, you need to re-wrap it with $.

For example, now we want to show the real address of the link at each link, first through each of the a tags, and then get the value of the href attribute, and then add to the link text behind.

After the change our plug-in code is:

$.fn.myplugin = function () {    this.css (' Color ', ' red ');     This.each (function () {        $ (this). Append ("" + $ (This). attr (' href '));}    );

Operation Result:

In this case, you can already write a simple jquery plugin, and it's not that hard.

The following starts the jquery plugin to write an important part of the parameter reception.

Supports chained calls

We all know that jquery is a very elegant feature that supports chained calls, and you can constantly invoke other methods after selecting a good DOM element.

To make the plug-in not break the chain call, just return it.

$.fn.myplugin = function () {    this.css (' Color ', ' red ');    Return This.each (function () {        $ (this). Append ("" + $ (This). attr (' href '));}    );
Let the plug-in receive parameters

A strong plug-in can be customized to the user, which requires us to provide the plug-in should be considered comprehensive, as far as possible to provide the appropriate parameters.

For example, now we don't want the link to only turn red, we let the user of the plugin define what color to display, to

It is convenient to do this, only require the user to pass in a parameter when the call. At the same time we receive in the plugin code. On the other hand, in order to be flexible, the user can not pass parameters, the plug-in will give the default value of the parameter.

The Extend method of jquery is usually used to handle the reception of plug-in parameters, as mentioned above, but that is the case of passing a single object to the Extend method, which is merged into jquery, so we can invoke the methods contained in the new merge object on jquery, Like the example above. When you pass more than one argument to the Extend method, it merges all the parameter objects into the first one. At the same time, if the object has the same name attribute, then the merge will overwrite the previous one.

With this, we can define an object in the plug-in that holds the default value of the plug-in parameter, merges the received parameter object onto the default object, and finally implements the user-specified value parameter using the specified value, using the plug-in default value for unspecified parameters.

For illustrative purposes, specify a parameter fontsize, which allows the font size to be set when the plugin is called.

$.fn.myplugin = function (options) {    var defaults={        ' color ': ' Red ',        ' fontSize ': ' 12px '    };    var settings=$.extend (defaults,options);    Return this.css ({        ' color ': Settings.color,        ' fontSize ': Settings.fontsize    });};

Now, we call the time to specify the color, the font size is not specified, will be used in the plug-in default value of 12px.

Calling code:

$ (' a '). Myplugin ({    

Operation Result:

Specify both color and font size

$ (' a '). Myplugin ({    ' color ': ' #2C9929 ',    ' fontSize ': ' 30px '});    

Operation Result:

Protect the default parameters.

Notice that the above code will change the value of the defaults when it calls extend, which is not good, because some things should be maintained as plug-ins, and if you want to use these defaults in subsequent code, it has been changed by the user's incoming parameters when you visit it again.

A good practice is to use a new empty object as the first parameter of $.extend, and defaults and user-passed parameter objects are immediately followed, so the benefit is that all values are merged into the empty object, protecting the default values inside the plug-in.

The following code:

$.fn.myplugin = function (options) {    var defaults={        ' color ': ' Red ',        ' fontSize ': ' 14px '    };    var settings=$.extend ({},defaults,options);    Return this.css ({        ' color ': Settings.color,        ' fontSize ': Settings.fontsize    });};

In this, the plug-in can receive and process parameters, you can write out more robust and flexible plug-ins. To write a complex plug-in, the amount of code is very large, and how to organize the code becomes a problem to be faced with. There is no good way to organize the code, the overall code will feel disorganized, but also not good maintenance, so the plug-in all the method attributes wrapped to an object, with object-oriented thinking to develop, will undoubtedly make the work much easier.

JQuery plug-in development tutorials

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.