search
HomeWeb Front-endJS TutorialFull analysis of jQuery plug-in development_jquery

There are two types of jQuery plug-in development: one is class-level plug-in development, that is, adding new global functions to jQuery, which is equivalent to adding methods to the jQuery class itself. jQuery's global functions are functions that belong to the jQuery namespace. The other is object-level plug-in development, which is to add methods to jQuery objects. The development of the two functions is described in detail below.
1. Class-level plug-in development
The most direct understanding of class-level plug-in development is to add class methods to the jQuery class, which can be understood as adding static methods. A typical example is the $.AJAX() function, which is defined in the jQuery namespace. Plug-in development at the class level can be extended in the following forms:
1.1 Add a new global function
To add a global function, we only need to define it as follows:
Java code

Copy code The code is as follows:

jQuery.foo = function() {
alert('This is a test . This is only a test.');
};

1.2 Add multiple global functions
To add multiple global functions, you can use the following definition:
Java code
Copy code The code is as follows:

jQuery.foo = function() {
alert( 'This is a test. This is only a test.');
};
jQuery.bar = function(param) {
alert('This function takes a parameter, which is "' param ' ".');
};

is called the same as a function: jQuery.foo();jQuery.bar(); or $.foo();$.bar ('bar');
1.3 Use jQuery.extend(object);
Java code

Copy code The code is as follows:

jQuery.extend({
foo: function() {
alert('This is a test. This is only a test.');
},
bar: function(param) {
alert('This function takes a parameter, which is "' param '".');
}
});

1.4 Using namespaces
Although in the jQuery namespace, we prohibit the use of a large number of javaScript function names and variable names. But it is still inevitable that some function or variable names will conflict with other jQuery plug-ins, so we are used to encapsulating some methods into another custom namespace.
Java code
Copy code The code is as follows:

1.jQuery.myPlugin = {
2.foo:function() {
3.alert('This is a test. This is only a test.');
4.},
5.bar:function(param ) {
6.alert('This function takes a parameter, which is "' param '".');
7.}
8.};

9 .Function using namespace is still a global function, the method used when calling:
10.$.myPlugin.foo();
11.$.myPlugin.bar('baz');
Passed With this trick (using separate plugin names), we can avoid namespace function conflicts.
2. Object-level plug-in development
Object-level plug-in development requires the following two forms:,
Form 1:
Java code
Copy code The code is as follows:

1.(function($){
2.$.fn.extend({
3. pluginName:function(opt,callback){
4. // Our plugin implementation code goes here.
5.}
6.})
7.})(jQuery);

Form 2:
Java code
Copy code The code is as follows:

1.(function($) {
2.$.fn.pluginName = function() {
3. // Our plugin implementation code goes here.
4.};
5 .})(jQuery);

A jQuery function is defined above, and the formal parameter is $. After the function definition is completed, pass the jQuery actual parameter in. It will be called and executed immediately. The advantage of this is that when we write a jQuery plug-in, we can also use the $ alias without causing conflict with the prototype.
2.1 Declare a name in the JQuery namespace
This is a single plug-in script. If your script contains multiple plug-ins, or reciprocal plug-ins (for example: $.fn.doSomething() and $.fn.undoSomething()), then you need to declare multiple function names. However, usually when we write a plug-in, we strive to use only one name to encompass all of its contents. Our example plugin is named "highlight"
Java code
Copy code The code is as follows:

1.$.fn.hilight = function() {
2. // Our plugin implementation code goes here.
3.};
4. Our plugin is called like this:
5.$('#myDiv').hilight();

But what if we need to decompose our implementation code into multiple functions? There are many reasons: design needs; This is easier or more readable to implement; and it is more object-oriented. This is a real hassle, breaking the functionality into multiple functions without adding unnecessary namespaces. We can do this out of recognition and utilization of functions as the most basic class objects in JavaScript. Just like other objects, functions can be specified as properties. Therefore, we have declared "hilight" as a jQuery property object. Any other properties or functions we need to expose can be declared as properties in the "hilight" function. Continue later.
2.2 Accepting the options parameter to control the behavior of the plugin
Let’s add the ability to specify the foreground and background colors to our plugin. We might pass the options to the plugin function as an options object. For example:
Java code
Copy code The code is as follows:

1.// plugin definition
2.$.fn.hilight = function(options) {
3. var defaults = {
4. foreground: 'red',
5. background: 'yellow'
6. };
7. // Extend our default options with those provided.
8. var opts = $.extend(defaults, options);
9. // Our plugin implementation code goes here.
10.};
11. Our plug-in can be called like this:
12.$('#myDiv').hilight({
13. foreground: 'blue'
14 .});

2.3 Exposing the default settings of the plug-in
One improvement we should make to the above code is to expose the default settings of the plug-in. This makes it easier for users of the plugin to overwrite and modify the plugin with less code. Next we start using function objects.
Java code
Copy code The code is as follows:

1.// plugin definition
2.$.fn.hilight = function(options) {
3. // Extend our default options with those provided.
4. // Note that the first arg to extend is an empty object -
5. // this is to keep from overriding our "defaults" object.
6. var opts = $.extend({}, $.fn.hilight.defaults, options);
7. / / Our plugin implementation code goes here.
8.};
9.// plugin defaults - added as a property on our plugin function
10.$.fn.hilight.defaults = {
11. foreground: 'red',
12. background: 'yellow'
13.};
14. Now users can include a line like this in their scripts:
15. //This only needs to be called once, and does not have to be called in the ready block
16.$.fn.hilight.defaults.foreground = 'blue';
17. Next we can use the plug-in like this method, which sets the foreground color to blue:
18.$('#myDiv').hilight();

Now users can include a line like this in their scripts Here:
Copy code The code is as follows:

//This only needs to be called once, and does not have to be called in the ready block
$.fn.hilight.defaults.foreground = 'blue';
Next we can use it like this The plugin's method, as a result it sets the blue foreground color:
$('#myDiv').hilight();
As you can see, we allow the user to write a line of code that sets the plugin's default foreground color. And users can still selectively override these new default values ​​when needed:
// Override the default background color of the plug-in
$.fn.hilight.defaults.foreground = 'blue';
// ...
// Call the plugin with a new default setting
$('.hilightDiv').hilight();
// ...
// Pass Configuration parameters to plugin methods to override default settings
$('#green').hilight({
foreground: 'green'
});

2.4 Appropriate Exposing some functions
will step by step extend your plug-in in interesting ways to the previous code (and let others extend your plug-in). For example, our plug-in implementation can define a function called "format" to format highlighted text. Our plug-in now looks like this, the implementation of the default format method is under the hiligth function.
Java code
Copy code The code is as follows:

1.// plugin definition
2.$.fn.hilight = function(options) {
3. // iterate and reformat each matched element
4. return this.each(function() {
5. var $this = $(this);
6. // ...
7. var markup = $this.html();
8. // call our format function
9. markup = $ .fn.hilight.format(markup);
10. $this.html(markup);
11. });
12.};
13.// define our format function
14.$.fn.hilight.format = function(txt) {
15.return '' txt '';
16.};

We easily support other properties in the options object by allowing a callback function to override the default settings. This is another great way to modify your plugins. The technique shown here is to further effectively expose the format function so that it can be redefined. With this technique, others can override your plugin by passing their own settings, in other words, so that others can write plugins for your plugin.
Considering the useless plugins we created in this article, you may be wondering when exactly these would be useful. A real example is the Cycle plug-in. This Cycle plug-in is a sliding display plug-in, which can support many internal transformation effects to scroll, slide, fade away, etc. But in practice, there is no way to define every type of effect that might be applied to a sliding change. That's where this extensibility is useful. The Cycle plugin exposes "transitions" objects to users, allowing them to add their own transformation definitions. The definition in the plug-in is like this:
Copy the code The code is as follows:

$.fn.cycle .transitions = {
// ...
};

This trick enables others to define and pass transformation settings to Cycle plugins.
2.5 Keep private functions private
This technique is very powerful in exposing part of your plugin to be overridden. But you need to think carefully about the exposed parts of your implementation. Once exposed, you need to keep in mind that any changes to parameters or semantics may break backward compatibility. A general rule of thumb is that if you're not sure whether to expose a particular function, then you probably don't need to do that.
So how do we define more functions without messing up the namespace or exposing the implementation? This is the function of closures. To demonstrate, we will add another "debug" function to our plugin. This debug function will output the selected element format to the firebug console. To create a closure, we will wrap the entire plugin definition in a function.
Java code
Copy code The code is as follows:

1.(function($) {
2. // plugin definition
3. $.fn.hilight = function(options) {
4. debug(this);
5. // ...
6 . };
7. // private function for debugging
8. function debug($obj) {
9. if (window.console && window.console.log)
10. window. console.log('hilight selection count: ' $obj.size());
11. };
12.// ...
13.})(jQuery);

Our "debug" method is not accessible from the outer closure and is therefore private to our implementation.
2.6 Support for Metadata plug-ins
Based on the plug-in you are writing, adding support for Metadata plug-ins can make it more powerful. Personally, I like this Metadata plugin because it lets you use a few "markup" options to override the plugin (which is very useful when creating examples). And supporting it is very simple. Update: A little optimization suggestion in the comments.
Java code
Copy code The code is as follows:

1.$.fn.hilight = function(options) {
2. // ...
3. // build main options before element iteration
4. var opts = $.extend({}, $.fn.hilight. defaults, options);
5. return this.each(function() {
6. var $this = $(this);
7. // build element specific options
8. var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
9. //...

These change lines do some Thing: It tests whether the Metadata plugin is installed. If it is installed, it can extend our options object by extracting the metadata line and adding it as the last parameter to JQuery.extend, which will now override any other options settings. We can drive behavior from "markup", if we select "markup":
When calling, we can write: jQuery.foo(); or $.foo();
Java code
Copy code The code is as follows:

1.
2 .

3. Have a nice day!
4.

5.< ;div class="hilight { foreground: 'orange' }">
6. Have a nice day!
7.

8.

9. Have a nice day!
10.


11. Now we can highlight which divs using only one line of script :
12.$('.hilight').hilight();

2.7 Integration
The following code makes our example complete:
Java code
Copy code The code is as follows:

1.// Create a closure
2.(function($) {
3. // Definition of plug-in
4. $.fn.hilight = function(options) {
5. debug(this);
6. // build main options before element iteration
7. var opts = $.extend({}, $.fn.hilight.defaults, options);
8. // iterate and reformat each matched element
9. return this.each(function () {
10. $this = $(this);
11. // build element specific options
12. var o = $.meta ? $.extend({}, opts, $this .data()) : opts;
13. // update element styles
14. $this.css({
15. backgroundColor: o.background,
16. color: o.foreground
17. });
18. var markup = $this.html();
19. // call our format function
20. markup = $.fn.hilight.format(markup );
21. $this.html(markup);
22. });
23. };
24. // Private function: debugging
25. function debug($ obj) {
26. if (window.console && window.console.log)
27. window.console.log('hilight selection count: ' $obj.size());
28. };
29. // Define the exposed format function
30. $.fn.hilight.format = function(txt) {
31. return '' txt ' ';
32. };
33. // Plug-in defaults
34. $.fn.hilight.defaults = {
35. foreground: 'red',
36. background : 'yellow'
37. };
38.// End of closure
39.})(jQuery);

This design has allowed me to create a powerful plug-in that conforms to the specification. I hope it enables you to do the same.
3. Summary
jQuery provides two methods for developing plug-ins, namely:
jQuery.fn.extend(object); Add methods to jQuery objects.
jQuery.extend(object); To extend the jQuery class itself. Add new methods to the class.
3.1 jQuery.fn.extend(object);
What is fn. Looking at the jQuery code, it's not hard to find.
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {//....
//......
};
Original jQuery.fn = jQuery.prototype. You are definitely familiar with prototype. Although JavaScript does not have a clear concept of classes, it is more convenient to use classes to understand it. jQuery is a very well-encapsulated class. For example, if we use the statement $("#btn1"), an instance of the jQuery class will be generated.
jQuery.fn.extend(object); To extend jQuery.prototype is to add "member functions" to the jQuery class. Instances of the jQuery class can use this "member function".
For example, we want to develop a plug-in to create a special edit box. When it is clicked, the content in the current edit box will be alerted. You can do this:
Copy code The code is as follows:

$.fn.extend({
alertWhileClick:function(){
$(this).click(function(){
alert($(this).val());
});
}
});
$("#input1").alertWhileClick(); //On the page:

$("#input1") is a jQuery instance, when it calls a member method After alertWhileClick, the extension is implemented. Every time it is clicked, it will pop up the current editing content first.
3.2 jQuery.extend(object);
Add a class method to the jQuery class, which can be understood as adding a static method. For example:
Copy code The code is as follows:

1.$.extend({
2.add:function(a,b){return a b;}
3.});

will add a "static method" called add for jQuery, and then you can introduce it For jQuery, use this method, $.add(3,4); //return 7
Statement
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
C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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.

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools