JQuery plugin development and jquery plugin
I. Classification
JQuery plug-ins are mainly divided into three types:
① Plug-ins that encapsulate object Methods
This plug-in encapsulates object methods and is used to operate jQuery objects obtained by selector. It is the most commonly used plug-in.
② Plug-ins that encapsulate global functions
Add independent functions to the jQuery namespace.
③ Selector plug-in
II. Key Points
① The file name of the jQuery plug-in is recommended to be jquery. [plug-in name]. js to avoid confusion with other javascript library plug-ins, such as jquery. color. js.
② All object methods should be appended to the jQuery. fn object, and all global functions should be appended to the jQuery object itself.
③ Inside the plug-in, this points to the jQuery object currently obtained through the selector. Unlike the general method, such as the click () method, the internal this points to the DOM element.
④ You can use this. eacj to traverse all elements.
⑤ All methods or function plug-ins should end with a semicolon; otherwise, problems may occur during compression. To be more secure, you can add a semicolon to the plug-in header to avoid the impact of others' nonstandard code on the plug-in.
⑥ The plug-in should return a jQuery object to ensure the chained operation of the plug-in. Unless the plug-in needs to return some quantities to be obtained, such as strings or arrays.
7. Avoid using $ as the alias of the jQuery object in the plug-in, instead of using the complete jQuery representation. This avoids 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.
3. Closure in Plug-ins
About closures: internal functions are allowed (that is, function definitions and function expressions are located in the body of another function ), in addition, these internal functions can access all the local variables, parameters, and other declared internal functions declared in their external functions, when one of these internal functions is called outside the external functions that contain them, a closure is formed. That is, the internal function will be executed after the external function returns. When this internal function is executed, it must still access the local variables, parameters, and other internal functions of its external function. The values of these local variables, parameters, and function declarations (initially) are the values returned by the external function, but they will also be affected by the internal function of the function.
Using the closure feature, you can avoid the impact of internal temporary variables on the global space, and continue to use $ as the jQuery alias within the plug-in.
Common jQuery plug-ins:
(Function (){
/* Place the code here */
})();
First define an anonymous function () {/* put the code here */}, and then enclose it in parentheses to (funcion () {/* put the code here */}) this form is finally executed using the () operator. Parameters can be passed in for internal functions.
Structure of Common jQuery plug-ins
// Note that for better compatibility, there is a semicolon before the start
; (Function ($) {// $ is used as the form parameter of the anonymous function.
/* Place the code here. You can use $ as the alias for jQuery */
}) (JQuery); // passing jQuery as a real parameter to an anonymous Function
Iv. Plug-in mechanism
1. jQuery provides two methods to expand jQuery functions, namely jQuery. fn. extend () and jQuery. extend.
① The jQuery. fn. extend () method is used to encapsulate the plug-in of the object method.
② The jQuery. extend () method is used to encapsulate plug-ins and Selector plug-ins of global functions.
2. Both methods receive an object parameter. The "name/value pair" of the object represents the "function or method name/function subject ".
3. In addition to extending jQuery objects, the jQuery. extend () method can also be used to extend existing object objects.
jQuery.extend(target,obj1,……[objN])
① Use one or more other objects to expand an object and return the extended object.
For example:
var settings={validate:false,limit:5,name:"foo"};
var options={validate:true,name:"bar"};
var newOptions=jQuery.extend(settings,options);
Result:
newOptions={validate:true,limit:5,name:”foo”};
② The jQuery. extend () method is often used to set a series of default parameters for the plug-in method.
Options = jQuery. extend ({
Name: "bar ",
Length: 5,
DataType: "xml"
}, Options);/* options is the passed parameter */
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.
5. Compile plug-ins
1. Plug-ins that encapsulate jQuery object Methods
① Color () plugin: jquery. color. js
// Note that for better compatibility, there is a semicolon before the start
; (Function ($) {// $ is used as the form parameter of the anonymous function.
/* Place the code here. You can use $ as the alias for jQuery */
$. Fn. extend ({
"Color": function (value ){
If (value = undefined ){
Return this.css ("color ");
} Else {
Return this.css ("color", value );
}
}
})
}) (JQuery); // passing jQuery as a real parameter to an anonymous Function
② Table row-changing plug-in: jquery. alertBgColor. js
; (Function ($ ){
$. Fn. extend ({
"AlertBgColor": function (options ){
Options = $. extend ({
Odd: "odd ",
Even: "even ",
Selected: "selected"
}, Options );
}
$ ("Tbody> tr: odd", this). addClass (options. add );
$ ("Tbody> tr: even", this). addClass (options. even );
$ ("Tbody> tr", this). click (function (){
// Determine whether or not it is selected
Var hasSelected = $ (this). hasClass (options. selected );
// If selected, the selected class is removed; otherwise, the selected class is added.
$ (This) [hasSelected? "RemoveClass": "addClass"] (
Options. selected)
// Search for the internal checkbox and set the corresponding attributes
. Find (': checked'). attr ('checked ',! HasSelected );
});
// If the single lens is selected by default, the color is high.
$ ("Tbody> tr: has (: checked)", this). addClass (options,
Selected );
Return this; // return this so that the method can be chained
});
}) (JQuery );
2. Plug-ins that encapsulate global functions
This type of plug-in adds a function to the jQuery namespace.
Remove left and right spaces: jquery. trim. js
;(function($){
$.extend({
ltrim:function(text){
return (text||"").replace(/^\s+/g,"");
},
rtrim:function(text){
return (text||"").replace('',/^\s);
}
});
})(jQuery);
3. Custom Selector
Between selector:
; $ (Function ($ ){
$. Extend ($. expr [":"], {
// The selector is part of the jQuery. expr [":"] object and is also an object. Therefore, you can directly use jQuery. extend () to extend it.
Between: function (a, I, m ){
Var tmp = m [3]. split (",");
Return tmp [0]-0 <I & I <tmp [1]-0;
}
});
}) (JQuery );
Plug-in application:
$(“function”(){
$(“div.between(2,5)”)…
});
The selector function accepts three parameters.
function(a,i,m){ //……. }
The first parameter a points to the DOM element currently traversed.
The second parameter I: refers to the index value of the DOM element currently traversed, starting from 0.
The third parameter m: The product (matched by match) further parsed by the jQuery Regular Expression parsing engine, which is an array
① M [0], the above $ ("div. between ()") example is: between (), which is the content of the jQuery selector to be further matched.
② M [1], here is the guiding negative of the selector, matching ":" In the example, that is, colon. It is not only possible to use ":", followed by the selector. You can also customize other selector guides.
③ M [2], that is, between in the example, determine whether the selector function is called.
④ M [3] is the number "2, 5" in the brackets in the example. It is very useful and is the most important parameter for programming selector functions.
⑤ M [4], which is not shown in the above example and rarely appears. For example, a selector such as "div: l (ss (dd)", m [4] points to the (dd) part. Note that it is a (dd) with parentheses ), not just dd. Note that the value of m [3] Is ss (dd) instead of ss.