


jQuery plug-in turns out to be so simple The mechanism and practice of jQuery plug-in_jquery
Types of jQuery plug-ins
1. Encapsulated object methods
This plug-in encapsulates object methods and is used to operate jQuery objects obtained through selectors. It is the most common plug-in. This type of plug-in can take advantage of the powerful advantages of jQuery selectors. A considerable number of jQuery methods are "inserted" into the kernel in this form within the jQuery script library, such as the parent() method and the appendTo() method. wait.
2. Encapsulate global functions
You can add independent functions to the jQuery namespace. For example, the commonly used jQuery.ajax() method and the jQuery.trim() method that removes leading and trailing spaces are all plugins attached to the kernel as global functions within jQuery.
3. Selector plug-in
Although jQuery’s selector is very powerful, in a few cases, you still need to use selector plug-ins to expand some of your favorite selectors.
The mechanism of jQuery plug-in
The mechanism of jQuery plug-in is very simple, which is to use the jQuery.fn.extend() and jQuery.extend() methods provided by jQuery to extend the functions of jQuery.
jQuery.fn.extend() is mostly used to extend the first of the three types mentioned above, and jQuery.extend() is used to extend the latter two plug-ins. Both methods accept one parameter, of type Object. The "name/value pairs" of the Object object respectively represent "function or method name/function body".
Some tips for writing jQuery plug-ins
1. It is recommended that the file name of the jQuery plug-in be named jquery.[plugin name].js to avoid confusion with other JS library plug-ins.
2. All object methods should be attached to the jQuery.fn object, and all global functions should be attached to the jQuery object itself.
3. Add a semicolon at the head of the plug-in to prevent other people’s irregular code from affecting the plug-in.
4. All methods or function plug-ins should end with a semicolon to avoid problems during compression
5. Unless the plug-in needs to return some variables that need to be obtained, the plug-in should return A jQuery object to ensure chainable operation of the plug-in.
6. It is helpful for the jQuery.extend() method to set the default parameters of the plug-in method and increase the usability of the plug-in.
jQuery plug-in structure
The jQuery plug-in structure is as follows:
;(function($){
/*Put the plug-in code here, you can use $ as an alias for jQuery*/
})(jQuery);
encapsulation jQuery object method plug-in practical
Function: Set the color of the selected element, get the color of the first selected element
Naming: jquery.color.js
Structure:
;(function($){
$.fn.extend( {
//Write the plug-in code here
});
})(jQuery);
Idea: Set a parameter value. If the parameter value is passed when calling, It is to set the color, otherwise it is to get the color. To get and set the color, you can use the css method provided by jQuery
Complete code:
;(function($){
$.fn.extend({
"color":function(value){
if(value==undefined){
return this.css("color");
}
else{
return this.css("color",value);
}
}
}) ;
})(jQuery);
Since the css() method has already determined the first element when getting the color, so here we directly use this.css("color") That’s it.
If it is a group of plug-ins, you can write it as follows:
;(function($){
$.fn.extend({
"color":function(value){
//Plug-in code
},
" border":function(value){
//Plug-in code
},
"background":function(value){
//Plug-in code
}
});
})(jQuery);
Plug-in test: http://demo.jb51.net/js/2012/jquery_demo/encapsulating jQuery object method plug-in Demo.html
Practice of encapsulating global function plug-in
Function: Remove the left or right spaces individually
Name: jquery.lrtrim.js
Structure:
;(function($){
$.extend({
ltrim:function(text){
//Plug-in code
},
rtrim:function( text){
//Plug-in code
}
});
})(jQuery);
Idea: This type of plug-in is added inside the jQuery namespace For a function, just use regular expressions.
Complete code:
;(function ($){
$.extend({
ltrim:function(text){
return (text||"").replace(/^s /g,"");
} ,
rtrim:function(text){
return (text||"").replace(/s $/g,"");
}
});
}) (jQuery);
Plug-in test: http://demo.jb51.net/js/2012/jquery_demo/encapsulating global function jQuery plug-in Demo.html
Self Define selector plug-in in action
jQuery is known for its powerful selectors, so how does jQuery’s selector work?
jQuery’s selection parser first uses a set of regular expressions to parse the selector, and then executes a function, called the selection function, for each parsed selector. Finally, it is decided whether to retain the element based on whether the return value of the selection function is true or false, so that the matching element node can be found.
For example, $("div:gl(1)"), this selector will first obtain all
The selector function accepts a total of 3 parameters, the form is as follows:
function (a,i,m){
//...
}
The first parameter is a, which refers to the current traversal to DOM element.
The second parameter is i, which refers to the index value of the DOM element currently traversed, starting from 0.
The third parameter is m, which is the product of further parsing by the jQuery regular parsing engine. It is an array: the most important one is m[3], in $("div:gl(1 )") is the number "1" in parentheses.
There are already lt, gt and eq selectors in jQuery, so here is a selector between the two.
Function: Select elements with index values between a and b (a
Naming: jquery.between.js
Structure:
;(function($){
$.extend($.expr[":"],{
between:function(a,i,m){
//Plug-in code
}
});
}) (jQuery);
Idea: Among the three parameters above, m[3] is in the form of "a, b", so separate m[3] with "," and then follow Compare the index value i, and return true if i is between the ranges represented by m[3], otherwise false
Complete code:
;(function($){
$.extend($.expr[":"],{
between :function(a,i,m){
var temp=m[3].split(",");
return temp[0]}
});
})(jQuery);
Note: temp[0] and temp[1] are used here to convert string numbers into numbers
Plug-in test: http://demo.jb51.net/js/2012/jquery_demo/jQuery custom selector plug-in DEMO.html
Summary
This article mainly introduces the jQuery plug-in Types, mechanisms, and actual combat for each type. I hope it can be helpful to everyone. I am also a beginner of jQuery, so everyone is welcome to try it out.
Reference book: "Sharp jQuery" (People's Posts and Telecommunications Publishing House)

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.
