search
HomeWeb Front-endJS TutorialHow to understand Jquery plug-in

How to understand Jquery plug-in

Sep 21, 2017 am 10:54 AM
jqueryplug-inunderstand

In actual development work, we will always encounter business needs such as scrolling, paging, calendar and other display effects. For those who have been exposed to jQuery and are familiar with the use of jQuery , the first thing that comes to mind is definitely to look for existing jQuery plug-ins to meet the corresponding display needs. There are a variety of jQuery plug-ins to choose from for some components commonly used in current pages. There are also many websites on the Internet that specifically collect jQuery plug-ins. Using the jQuery plug-in can indeed bring convenience to our development work, but if you only use it simply and don’t understand the principles, you will encounter problems during use or customize the development of the plug-in. There will be many doubts. The purpose of this article is to quickly understand the development principles of jQuery plug-ins and master the basic skills of jQuery development.


Before developing jQuery plug-ins, you must first know two questions: What is a jQuery plug-in? How to use jQuery plug-in?
The first question, jQuery plug-in is a method used to extend jQuery prototype object. Simply put, jQuery plug-in isjQueryA method of the object. In fact, after answering the first question, you will know the answer to the second question. The way to use the jQuery plug-in is to call the jQuery object method.

Let’s look at an example first: $("a").css("color","red"). We know that each jQuery object will contain the DOM operation method defined in jQuery. Here, the $ method is used to select the a element and return an ## of the a element. #jQuery object, this object can use the DOM operation method defined in jQuery. So how does the jQuery object obtain these methods? In fact, jQuery internally defines a jQuery.fn object. Looking at the jQuery source code, you can find jQuery.fn=jQuery.prototype, that is It is said that the jQuery.fn object is the prototype object of jQuery, and the DOM operation methods of jQuery are all in jQuery.fnDefined on the object, then the jQuery object can inherit these methods through the prototype.

1. Basic jQuery plug-in

After knowing the above knowledge, we can write a simple

jQuery plug-in. If I now need a jQuery plug-in to change the color of the label content, I can implement the plug-in in the following way:

$.fn.changeStyle = function(colorStr){
         this.css("color",colorStr);
}

Then use the plug-in in the following way:

$("p").changeStyle("red");

When the plug-in is called, this inside the plug-in is the

jQuery object currently calling the plug-in. In this case, each tag selected using the $() method will be called changeStyle()When plug-in, the css() method will be used to reset the color style.

2. jQuery plug-in that satisfies chain call

Chain call is a major feature of

jQuery, a general plug-in should followjQuery style, meeting the requirements of chain calls. The way to implement chain calling is also very simple:

$.fn.changeStyle = function(colorStr){
         this.css("color",colorStr);         
         return this;
}

Then when using it, you can chain call other methods:

$("p").changeStyle("red").addClass("red-color");

The key point to implement chain calling is just one line of code

return this, this line of code is added to the plug-in, then after the plug-in is executed, the current jQuery object will be returned, and then you can continue to call other jQuery after the plug-in method method.

3. jQuery plug-in to prevent $ symbol pollution

There are many js libraries that use the

$ symbol, although jQuery You can use the jQuery.noConflict() method to hand over the right to use the $ symbol, but if you define a plug-in, use the $.fn object to define it, Then when these plug-ins are used, they will be affected by other js libraries that use $ variables. In this case, we can use the immediate execution function to encapsulate the plug-in by passing parameters. The form is as follows:

(function($){
     $.fn.changeStyle = function(colorStr){
         this.css("color",colorStr);        
         return this;
     }
}(jQuery));

Because the immediate execution function is used, the $ at this time only belongs to the function scope of this immediate execution function, so that the pollution of the

$ symbol can be avoided.

4. A jQuery plug-in that can accept parameters

Continuing with the above example, if I also want to add a function to this plug-in to set the text size of the label element content, then I can implement it like this:

(function($){
     $.fn.changeStyle = function(colorStr,fontSize){
         this.css("color",colorStr).css("fontSize",fontSize+"px");        
         return this;
     }
}(jQuery));

The above plug-in parameter passing method is suitable for situations where there are relatively few parameters. If there are more parameters that need to be passed to the plug-in, we can define a parameter object and then pass the parameters that need to be passed to the plug-in. Parameters given to the plug-in are placed in the parameter object. The plug-in is defined as follows:

(function($){
     $.fn.changeStyle = function(option){
         this.css("color",option.colorStr).css("fontSize",option.fontSize+"px");        
         return this;
     }

}(jQuery));

Usage:


$("p").changeStyle({colorStr:"red",fontSize:14}); Put Another advantage of putting the parameters in an object and passing them to the plug-in is that we can define some default values ​​for some parameters inside the plug-in, for example:

(function($){
     $.fn.changeStyle = function(option){
          var defaultSetting = { colorStr:"green",fontSize:12};
          var setting = $.extend(defaultSetting,option);
          this.css("color",setting.colorStr).css("fontSize",setting.fontSize+"px");        
         return this;
     }
}(jQuery));

上面的代码用到了$.extend方法,这个方法在这里的用法就是合并两个对象,即把后面一个对象的存在的属性值赋值给第一个对象,具体用法可以参考这里。$.extend方法还有一种作用是用来扩展jQuery对象本身。
这样定义的插件,我们在使用时如果不传fontSize,那么使用这个插件的jQuery对象标签的内容会被设置成默认的12px
使用方式:
$("p").changeStyle({colorStr:"red"});
注意:在为插件定义默认参数时,一定要把默认参数写在插件方法内部,这样默认参数的作用域就在插件内部。


总结

定义插件的方式除了上面说的用$.fn来定义,还有另外一种方式来定义插件,那就是使用$.fn.extend方法。类似下面的写法:

//注意为了更好的兼容性,开始前有个分号;(function($){
     $.fn.extend({         
         changeStyle:function(option){             
         var defaultSetting = { colorStr:"green",fontSize:12};         
         var setting = $.extend(defaultSetting,option);         
         this.css("color",setting.colorStr).css("fontSize",setting.fontSize+"px");        
         return this; 
          }
     });
}(jQuery));//这里将Jquery作为实参传递给匿名函数

PS: $.extend方法和$.fn.extend方法都可以用来扩展jQuery功能,通过阅读jQuery源码我们可以发现这两个方法的本质区别,那就是$.extend方法是在jQuery全局对象上扩展方法,$.fn.extend方法是在$选择符选择的jQuery对象上扩展方法。所以扩展jQuery的公共方法一般用$.extend方法,定义插件一般用$.fn.extend方法。

The above is the detailed content of How to understand Jquery plug-in. For more information, please follow other related articles on the PHP Chinese website!

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
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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 Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

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

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

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.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

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.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.