


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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











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.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.
