jquery Learning (iv)-How to write a custom jquery plugin

Source: Internet
Author: User

From the Sharp jquery second Edition

Let's start by showing you how to encapsulate an efficient plugin that fits your needs with existing methods and functions.

Jquery plug-ins are divided into 3 categories: plug-ins for encapsulating object methods, plug-ins for encapsulating global functions, custom selector plug-ins, and before introducing the three types of plug-ins, let's start by understanding the basics of writing plug-ins (this goes from Aspwzmuma and sharp jquery):

A. The plugin's file naming recommendation follows jquery. [Plugin name].js rules to facilitate the distinction with other JS files, such as the new plugin file jquery.newplugin.js.

B. Object-level plug-ins, all methods should be attached to the Jquery.fn principal object; class-level plug-in, all methods should be attached to the jquery object

C. Inside the plug-in, this represents the object acquired through the jquery selector, unlike the general method. For example: the Click () method, internal this refers to the DOM object that binds click.

D. You can traverse all the elements through $.each.

E. Regardless of the object level or class level plug-in, the end must end with a semicolon, otherwise the error message appears when the file is compressed. To avoid the hassle, we can add a semicolon at the beginning of the plugin.

F. The plugin should return a jquery object to ensure that it can be chained. Unless the plug-in is a parameter that needs to return a string or a number.

G. Avoid using $ as an alias for jquery objects within a plugin, but instead use full jquery to represent them. Doing so avoids conflicts. However, if we stick to $, we can circumvent the problem by closing the packet.

such as the following code:

;(function ($) {

Var foo;

Var bar=function () {

}

$.bar=bar;

}) (JQuery)

H.jquery provides two ways to extend the functionality of jquery. The first method, $.fn.extend (), is suitable for creating the first type of plug-in, the second method $.extend (), and applies to the latter two plugins.

1. Plug-in for encapsulating object methods

What is a plug-in for encapsulating object methods? To put it bluntly is to encapsulate the object method, which can then be manipulated by the object obtained by the jquery selector, such as $ ("element"). Action (), this The action is the encapsulated object, like the parent (),addclass () method of jquery . The code is as follows:

;(function ($) {
$.fn.extend ({
Color settings
"Color": function (value) {
return this.css ("Color", value);
}
Table interlaced, check Highlight (checkbox selected, color highlight)
, "Table": function (Options) {
Options= $.extend ({
Odd: "Odd",
Even: "Even",
Selected: "Selected"
},options);
$ ("tbody>tr:odd", this). addclass (options.odd);
$ ("Tbody>tr:even", this). addclass (Options.even);
$ ("Tbody>tr", this). Click (function () {
var hasselected=$ (this). Hasclass (options.selected);
$ (this) [hasselected?] Removeclass ":" AddClass "] (options.selected)
. Find (": CheckBox"). Prop ("Checked",!hasselected);
});
If the Radio box is selected by default, the row is highlighted
$ ("Tbody>tr:has (: Checked)", this). addclass (options.selected);
return this; Returns this so that the method can be chained
}

});
}) (JQuery)

called

$ ("div"). Color ("red");

$ ("table"). Table ({

Odd: "Odd",
Even: "Even",
Selected: "Selected"
});

2. Plug-in that encapsulates global functions

This type of plug-in is a function added in the jQuery name space, the following to remove the string to the left or right space for example, the code is as follows:

;(function ($) {
$.extend ({
Ltrm:function (value) {
Return (value | | ""). Replace (/^\s/g, "");
},
Rtrim:function (value) {
Return (value | | ""). Replace (/\s+$/g, "");
}
});
}) (JQuery)

called

Var STR1=$.LTRM (str);

3. Custom Selector Plugin

Although the jQuery selector is already powerful, it doesn't mean it's perfect, and developers sometimes need a powerful selector that fits their needs. This is the way jquery provides user-definable selectors that play a big role in making jquery selectors more sophisticated. Nonsense not much to say, directly on the code:

;(function ($) {

$.extend (jquery.expr[":"], {

Between:function (A, I, M) {

will pass in the m[3] comma as a delimiter, cut into an array

var tmp=m[3].split (",");

Return tmp[0]-0<i&&i<tmp[1]-0;

}

});

}) (JQuery);

Over hereaThat points to the current traversedDOMelements;Irefers to the current traversal to theDOMthe index value of the element, from0to begin with;mis ajqueryThe regular parsing engine further parses the product and returns an array, below which we$("DIV:GT (1)")For example AnalysismParameters:
M[0]jqueryto further match the content, 'GT (1)';

M[1] Selector Guide, the above example is a colon ': ', the user can customize the boot character;

M[2] The selector function to invoke, in the case of the GT () function ;

M[3] represents the parameters of the selector function.

JQuery Learning (iv)-How to write a custom jquery plugin

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.