Home Web Front-end JS Tutorial Example explanation of jQuery plug-in development

Example explanation of jQuery plug-in development

Jun 25, 2017 am 09:20 AM
jquery how develop master plug-in

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? jQueryHow to use the plug-in?
The first question, jQueryThe plug-in is a method used to extend the jQuery prototype object. Simply put, the jQuery plug-in is jQuery A 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 we use the $ method to select a element, returns a jQuery object of the a element. 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.

Basic version of jQuery plug-in
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);
}
Copy after login

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 currently calling the plug-in. Object, in this case, each tag selected using the $() method will be reset using the css() method when calling the changeStyle() plug-incolor Style.

jQuery plug-in that satisfies the chain call
Chain call is a major feature of jQuery. A general plug-in should follow the jQuery style and satisfy the chain call Call request. The way to implement chain calls is also very simple:

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

Then when using it, you can chain call other methods:
$("p").changeStyle("red"). addClass("red-color");
The key point to realize the chain call is one line of codereturn this. If 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 methods after the plug-in method.

jQuery plug-in to prevent $ symbol pollution
There are many js libraries that use the $ symbol, although jQuery can use The jQuery.noConflict() method hands over the right to use the $ symbol, but if the plugins are defined using the $.fn object, then these plugins will be used by other users. $The impact of the js library on 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));
Copy after login

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

JQuery plug-in that can accept parameters
Continuing 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 achieve it like this:

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

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 put the parameters that need to be passed to the plug-in 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));
Copy after login

使用方式:$("p").changeStyle({colorStr:"red",fontSize:14});
把参数放到一个对象中传给插件还有一个好处就是我们可以在插件内部为一些参数定义一些缺省值,例如:

(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));
Copy after login

上面的代码用到了$.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));
Copy after login

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

The above is the detailed content of Example explanation of jQuery plug-in development. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

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

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)

Four recommended AI-assisted programming tools Four recommended AI-assisted programming tools Apr 22, 2024 pm 05:34 PM

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

Share three solutions to why Edge browser does not support this plug-in Share three solutions to why Edge browser does not support this plug-in Mar 13, 2024 pm 04:34 PM

When users use the Edge browser, they may add some plug-ins to meet more of their needs. But when adding a plug-in, it shows that this plug-in is not supported. How to solve this problem? Today, the editor will share with you three solutions. Come and try it. Method 1: Try using another browser. Method 2: The Flash Player on the browser may be out of date or missing, causing the plug-in to be unsupported. You can download the latest version from the official website. Method 3: Press the "Ctrl+Shift+Delete" keys at the same time. Click "Clear Data" and reopen the browser.

What is the Chrome plug-in extension installation directory? What is the Chrome plug-in extension installation directory? Mar 08, 2024 am 08:55 AM

What is the Chrome plug-in extension installation directory? Under normal circumstances, the default installation directory of Chrome plug-in extensions is as follows: 1. The default installation directory location of chrome plug-ins in windowsxp: C:\DocumentsandSettings\username\LocalSettings\ApplicationData\Google\Chrome\UserData\Default\Extensions2. chrome in windows7 The default installation directory location of the plug-in: C:\Users\username\AppData\Local\Google\Chrome\User

Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Apr 07, 2024 am 09:10 AM

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

Learn how to develop mobile applications using Go language Learn how to develop mobile applications using Go language Mar 28, 2024 pm 10:00 PM

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

Which Linux distribution is best for Android development? Which Linux distribution is best for Android development? Mar 14, 2024 pm 12:30 PM

Android development is a busy and exciting job, and choosing a suitable Linux distribution for development is particularly important. Among the many Linux distributions, which one is most suitable for Android development? This article will explore this issue from several aspects and give specific code examples. First, let’s take a look at several currently popular Linux distributions: Ubuntu, Fedora, Debian, CentOS, etc. They all have their own advantages and characteristics.

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Understanding VSCode: What is this tool used for? Understanding VSCode: What is this tool used for? Mar 25, 2024 pm 03:06 PM

"Understanding VSCode: What is this tool used for?" 》As a programmer, whether you are a beginner or an experienced developer, you cannot do without the use of code editing tools. Among many editing tools, Visual Studio Code (VSCode for short) is very popular among developers as an open source, lightweight, and powerful code editor. So, what exactly is VSCode used for? This article will delve into the functions and uses of VSCode and provide specific code examples to help readers

See all articles