JQuery Plugin Development

Source: Internet
Author: User

After learning the JQuery plug-in development, you can encapsulate your usual features into plug-ins to facilitate the use of different projects.

The plug-in development tutorials on the JQuery website are good and easy to understand.

There are 2 important APIs in jquery that are related to plugin authoring.

    1. Jquery.extend (object) is $.extend (object)
    2. JQuery.fn.extend (object) is $.fn.extend (object)

These 2 APIs are designed to add their own functionality to jquery in the form of plugins.

But there is a difference in meaning.

1.1 $.extend (object)

This function is used to extend the jQuery itself, that is, to extend the "$".

Examples are as follows:

<! DOCTYPE html>

First click the [Btn-test] button, prompt for no test method, then click [Btn-extend] button to expand the $ itself.

Click the [Btn-test] button again to execute the extended $.test () function.

1.2 $.fn.extend (object)

This function is used to provide new methods for JQuery objects.

The so-called jquery objects, the most common ones we usually get through the jquery selector, such as: $ ("#id"), $ (". Class"), etc.

<! DOCTYPE html>

First click the [Btn-test] button, prompt for no test method, then click [Btn-extend] button to expand the $ object.

Click the [Btn-test] button again to execute the extended $.fn.test () function.

Before you write a jQuery plugin, be sure to understand the difference between "$ itself" and "$ object". ($ is jQuery)

That is to understand the difference between $.extend and $.fn.extend.

2. UI-related plugins

In general, there are few plug-ins that are purely UI-related and are used in conjunction with the UI and functionality, such as the JQuery UI library.

The following example is primarily intended to illustrate how to use the JQuery plugin, so it is only relevant to the UI.

2.1 Example 1: setting colors uniformly

Sample HTML:

<! DOCTYPE html>

Example JQuery plugin:

/* jquery plugin for Test * filename:jquery-plugin.js *///The following format is also common notation for jquery plugins (function ($) {    $.fn.toggle_back = f Unction () {        if (this.css ("background-color") = = "RGB (255, 0, 0)")            this.css ("Background-color", "green");        else            this.css ("Background-color", "Red");    };} (JQuery));

You can toggle the background color of all smalldiv by clicking the button on the HTML page.

2.2 Example 2: setting colors individually

This example is slightly more complicated than the one above, and example 1 above is a uniform set of background colors for all smalldiv, not flexible enough.

This example sets the background color based on the $.fn.each function of jQuery for each Smalldiv class.

(The HTML part of the code is the same as Example 1)

/* jquery plugin for Test * filename:jquery-plugin.js *///The following format is also common notation for jquery plugins (function ($) {    $.fn.toggle_back = f Unction () {This.each () (        function () {            var div = $ (this);            if (Div.hasclass ("Red")) {                Div.removeclass ("Red");                Div.addclass ("green");                Div.css ("Background-color", "green");            }            else {                Div.removeclass ("green");                Div.addclass ("Red");                Div.css ("Background-color", "Red");            }        );        return this;    };} (JQuery));

Here are 2 places to note:

1. Meaning of this in the code

This.each (function () {

Here is the jquery object, which is the object obtained by a selector such as $ ("#id"), $ (". Class").

* Note that this is the location of the $.fn.toggle_back in the main function body.

var div = $ (this);

This is the DOM object, so you can become a JQuery object by using $ (this).

As for why this is the individual DOM objects in each, it is because each implementation converts the JQuery object to a DOM object.

2. End of plugin code return this;

Here is the reason to return this; is to implement the chain expression of jQuery. That is, return this; After that, you can then call other jQuery functions.

such as $ (". Class"). Toggle_back (). CSS ("Color", "red");

In Example 2 above, $ ("#btn-plugin"). The click function can be changed to the following:

$ ("#btn-plugin"). Click (function () {     $ (". Smalldiv"). Toggle_back (). CSS ("Color", "red");});

3. Functional plug-in

The following is an example of a date conversion that describes how a functional plug-in is written.

HTML section:

<! DOCTYPE html>

The plugin JS is simply converted to a time format, just to demonstrate:

/* jquery plugin for Test * filename:jquery-plugin.js * * (function ($) {$.fn.dt_format = function (dt) {This.ea            CH (function () {var elem = $ (this);            if (Elem.hasclass ("date")) Elem.text ($.fn.dt_format.date (DT));            if (Elem.hasclass ("Time")) Elem.text ($.fn.dt_format.time (DT));        if (Elem.hasclass ("datetime")) Elem.text ($.fn.dt_format.datetime (DT));        });    return this;    };        $.fn.dt_format.date = function (dt) {var year = dt.getfullyear ();        var month = Dt.getmonth () + 1;        var day = Dt.getdate ();    Return year + "years/" + month + "month/" + Day + "date";    };        $.fn.dt_format.time = function (dt) {var hour = dt.gethours ();        var minute = Dt.getminutes ();        var second = Dt.getseconds ();    Return hour + "when:" + Minute + "points:" + second + "seconds";    }; $.fn.dt_format.datetime = function (dt) {return $.fn.dt_format.date (dt) + "" + $.fn.dt_format. time (DT); };} (JQuery));

Click the buttons on the HTML page to convert different time formats and display them on the page.

4. Default parameters for plugins

The above plug-in requires a parameter, if the call plug-in without parameters, it will lead to JS error.

For a better user experience, add the default parameters (that is, the current time) to the plugin below.

The new plugin JS is as follows:

/* jquery plugin for Test * filename:jquery-plugin.js */(function ($) {$.fn.dt_format = function (options) {// The user's options and default parameters defaults merge, if there are duplicates, preference options//$.extend The first parameter here is an empty object, the reason behind the explanation of var settings = $.exte                nd ({}, $.fn.dt_format.defaults, options);            This.each (function () {var elem = $ (this);            if (Elem.hasclass ("date")) Elem.text ($.fn.dt_format.date (SETTINGS.DT));            if (Elem.hasclass ("Time")) Elem.text ($.fn.dt_format.time (SETTINGS.DT));        if (Elem.hasclass ("datetime")) Elem.text ($.fn.dt_format.datetime (SETTINGS.DT));        });    return this;    };    The default parameter $.fn.dt_format.defaults = {dt:new Date () is provided here,};        $.fn.dt_format.date = function (dt) {var year = dt.getfullyear ();        var month = Dt.getmonth () + 1;        var day = Dt.getdate ();    Return year + "years/" + month + "month/" + Day + "date";    }; $.fn.dt_format.time = FuNction (DT) {var hour = dt.gethours ();        var minute = Dt.getminutes ();        var second = Dt.getseconds ();    Return hour + "when:" + Minute + "points:" + second + "seconds";    };            $.fn.dt_format.datetime = function (dt) {return $.fn.dt_format.date (dt) + "" + $.fn.dt_format.time (DT); };} (JQuery));

You can call plug-ins in HTML without parameters.

$ (function () {    $ ("#btn-plugin"). Click (function () {        $ ("H2"). Dt_format ();//Here you can do not enter parameters, use default parameters.    });

Add : When merging parameters, $.extend is used to combine all parameters into a large JSON object, with the same key, followed by parameters that overwrite the previous parameters.

The first parameter of $.extend is {}, so this is because the first argument is broken after merging, so defaults cannot be placed first.

The example is as follows: (you can see the output in Chrome's console window)

<! DOCTYPE html>

5. Public and private functions in plugins

Although JavaScript is not a purely object-oriented language, it can also construct public/private functions similar to other object-oriented languages through its powerful closure capabilities.

* In the example of a functional plug- in * 3 functions $.fn.dt_format.date, $.fn.dt_format.time, $.fn.dt_format.datetime are public functions, can be overridden by the plugin user.

For example, replace the HTML of the example above with the following: (Overwrite the $.fn.dt_format.datetime method in the plugin)

<! DOCTYPE html>

If you do not want to expose the method, change the 3 function definition methods:

/* jquery plugin for Test * filename:jquery-plugin.js */(function ($) {$.fn.dt_format = function (options) {VA                R settings = $.extend ({}, $.fn.dt_format.defaults, options);            This.each (function () {var elem = $ (this);            if (Elem.hasclass ("date")) Elem.text (date (SETTINGS.DT));            if (Elem.hasclass ("Time")) Elem.text (Time (SETTINGS.DT));        if (Elem.hasclass ("datetime")) Elem.text (DateTime (SETTINGS.DT));        });    return this;    };    $.fn.dt_format.defaults = {dt:new Date (),};        var date = function (dt) {var year = dt.getfullyear ();        var month = Dt.getmonth () + 1;        var day = Dt.getdate ();    Return year + "years/" + month + "month/" + Day + "date";    };        var time = function (dt) {var hour = dt.gethours ();        var minute = Dt.getminutes ();        var second = Dt.getseconds ();    Return hour + "when:" + Minute + "points:" + second + "seconds";  };  var datetime = function (dt) {return date (dt) + "" + Time (DT); };} (JQuery));

This way, the plugin user cannot overwrite the date, time, and DateTime methods.

6. Note Points written by the plugin

is summed up in the plugin tutorial on the official JQuery website:

    1. Do not customize the syntax
    2. Do not write the ID or class of the dead element and open it in the form of options.
    3. Provide callback

JQuery Plugin Development

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.