Home Web Front-end JS Tutorial jQuery plug-in turns out to be so simple The mechanism and practice of jQuery plug-in_jquery

jQuery plug-in turns out to be so simple The mechanism and practice of jQuery plug-in_jquery

May 16, 2016 pm 05:56 PM
jquery plugin

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:

Copy code The code 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:
Copy code The code is as follows:

;(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:
Copy code The code is as follows :

;(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:
Copy the code The code is 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:
Copy code The code is as follows:

;(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:
Copy code The code is as follows:

;(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
elements, then implicitly traverse these
elements, and select these < The ;div> element is used as a parameter, and some parameters such as "1" in parentheses are passed to the corresponding selector function of gt for judgment. If true is returned, it is retained, otherwise it is not retained. The result is a collection of
elements that meet the requirements.

The selector function accepts a total of 3 parameters, the form is as follows:
Copy code The code 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:
Copy code The code is as follows:

;(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:
Copy Code The code is as follows:

;(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)
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

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...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

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 using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

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...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

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 difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

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. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

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/)...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

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

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

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.

See all articles