Detailed explanation of jQuery plug-in packaging steps
This time I will bring you a detailed explanation of the jQuery plug-in encapsulation steps. What are the precautions for jQuery plug-in encapsulation? The following is a practical case, let’s take a look.
Extending jQuery plug-ins and methods is very powerful and can save a lot of development time. This article will outline the basics, best practices, and common pitfalls of jQuery plugin development.1. Getting Started
Writing a jQuery plug-in starts by adding new functional attributes to jQuery.fn. The object attributes added here are The name is the name of your plug-in: . The code is as follows:jQuery.fn.myPlugin = function(){ //你自己的插件代码 };
(function ($) { $.fn.myPlugin = function () { //你自己的插件代码 }; })(jQuery);
2. Environment
Now, we can start writing the actual plug-in code. However, before that, we must have an idea of the environment in which the plug-in is located. In the scope of the plug-in, the this keyword represents the jQuery object that the plug-in will execute. A common misunderstanding is easy to occur here, because in other jQuery functions that contain callbacks, the this keyword represents the native DOM element. This often causes developers to mistakenly wrap the this keyword in jQuery unnecessarily, as shown below. . The code is as follows:(function ($) { $.fn.myPlugin = function () { //此处没有必要将this包在$号中如$(this),因为this已经是一个jQuery对象。 //$(this)等同于 $($('#element')); this.fadeIn('normal', function () { //此处callback函数中this关键字代表一个DOM元素 }); }; })(jQuery); $('#element').myPlugin();
3. Basic knowledge
Now, we understand the basic knowledge of jQuery plug-in, Let's write a plugin that does something. . The code is as follows:(function ($) { $.fn.maxHeight = function () { var max = 0; this.each(function () { max = Math.max(max, $(this).height()); }); return max; }; })(jQuery); var tallest = $('p').maxHeight(); //返回高度最大的p元素的高度
4. Maintain Chainability
Many times, the intention of a plug-in is simply to modify the collected elements in some way and pass them on to the next method in the chain. This is the beauty of jQuery's design and one of the reasons jQuery is so popular. Therefore, to maintain a plugin's chainability, you must ensure that your plugin returns the this keyword. . The code is as follows:(function ($) { $.fn.lockDimensions = function (type) { return this.each(function () { var $this = $(this); if (!type || type == 'width') { $this.width($this.width()); } if (!type || type == 'height') { $this.height($this.height()); } }); }; })(jQuery); $('p').lockDimensions('width').CSS('color', 'red');
5. Default values and options
For more complex plug-ins that provide many customizable options, it is best to have a local Default settings that can be extended when the plugin is called (by using $.extend). So instead of calling a plugin with a bunch of parameters, you can call it with an object parameter containing the settings you want to override. . The code is as follows:(function ($) { $.fn.tooltip = function (options) { //创建一些默认值,拓展任何被提供的选项 var settings = $.extend({ 'location': 'top', 'background-color': 'blue' }, options); return this.each(function () { // Tooltip插件代码 }); }; })(jQuery); $('p').tooltip({ 'location': 'left' });
{ 'location': 'left', 'background-color': 'blue' }
7. Plug-in method
在任何情况下,一个单独的插件不应该在jQuery.fnjQuery.fn对象里有多个命名空间。
. 代码如下:
(function ($) { $.fn.tooltip = function (options) { // this }; $.fn.tooltipShow = function () { // is }; $.fn.tooltipHide = function () { // bad }; $.fn.tooltipUpdate = function (content) { // !!! }; })(jQuery);
这是不被鼓励的,因为它.fn使.fn命名空间混乱。 为了解决这个问题,你应该收集对象文本中的所有插件的方法,通过传递该方法的字符串名称给插件以调用它们。
. 代码如下:
(function ($) { var methods = { init: function (options) { // this }, show: function () { // is }, hide: function () { // good }, update: function (content) { // !!! } }; $.fn.tooltip = function (method) { // 方法调用 if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method' + method + 'does not exist on jQuery.tooltip'); } }; })(jQuery); //调用init方法 $('p').tooltip(); //调用init方法 $('p').tooltip({ foo: 'bar' }); // 调用hide方法 $(‘p').tooltip(‘hide'); //调用Update方法 $(‘p').tooltip(‘update', ‘This is the new tooltip content!');
这种类型的插件架构允许您封装所有的方法在父包中,通过传递该方法的字符串名称和额外的此方法需要的参数来调用它们。 这种方法的封装和架构类型是jQuery插件社区的标准,它被无数的插件在使用,包括jQueryUI中的插件和widgets。
八、事件
一个鲜为人知bind方法的功能即允许绑定事件命名空间。 如果你的插件绑定一个事件,一个很好的做法是赋予此事件命名空间。 通过这种方式,当你在解除绑定的时候不会干扰其他可能已经绑定的同一类型事件。 你可以通过追加命名空间到你需要绑定的的事件通过 ‘.'。
. 代码如下:
(function ($) { var methods = { init: function (options) { return this.each(function () { $(window).bind('resize.tooltip', methods.reposition); }); }, destroy: function () { return this.each(function () { $(window).unbind('.tooltip'); }) }, reposition: function () { //... }, show: function () { //... }, hide: function () { //... }, update: function (content) { //... } }; $.fn.tooltip = function (method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.tooltip'); } }; })(jQuery); $('#fun').tooltip(); //一段时间之后… … $(‘#fun').tooltip(‘destroy');
在这个例子中,当tooltip通过init方法初始化时,它将reposition方法绑定到resize事件并给reposition非那方法赋予命名空间通过追加.tooltip。 稍后, 当开发人员需要销毁tooltip的时候,我们可以同时解除其中reposition方法和resize事件的绑定,通过传递reposition的命名空间给插件。 这使我们能够安全地解除事件的绑定并不会影响到此插件之外的绑定。
九、数据
通常在插件开发的时候,你可能需要记录或者检查你的插件是否已经被初始化给了一个元素。 使用jQuery的data方法是一个很好的基于元素的记录变量的途径。尽管如此,相对于记录大量的不同名字的分离的data, 使用一个单独的对象保存所有变量,并通过一个单独的命名空间读取这个对象不失为一个更好的方法。
. 代码如下:
(function ($) { var methods = { init: function (options) { return this.each(function () { var $this = $(this), data = $this.data('tooltip'), tooltip = $('<p />', { text: $this.attr('title') }); // If the plugin hasn't been initialized yet if (!data) { /* Do more setup stuff here */ $(this).data('tooltip', { target: $this, tooltip: tooltip }); } }); }, destroy: function () { return this.each(function () { var $this = $(this), data = $this.data('tooltip'); // Namespacing FTW $(window).unbind('.tooltip'); data.tooltip.remove(); $this.removeData('tooltip'); }) }, reposition: function () { // ... }, show: function () { // ... }, hide: function () { // ... }, update: function (content) { // ... } }; $.fn.tooltip = function (method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.tooltip'); } }; })(jQuery);
将数据通过命名空间封装在一个对象中,可以更容易的从一个集中的位置读取所有插件的属性。
十、总结和最佳做法
编写jQuery插件允许你做出库,将最有用的功能集成到可重用的代码,可以节省开发者的时间,使开发更高效。 开发jQuery插件时,要牢记:
1.始终包裹在一个封闭的插件:
. 代码如下:
(function($) { /* plugin goes here */ })(jQuery);
2.不要冗余包裹this关键字在插件的功能范围内
3.除非插件返回特定值,否则总是返回this关键字来维持chainability 。
4.传递一个可拓展的默认对象参数而不是大量的参数给插件。
5.不要在一个插件中多次命名不同方法。
3.始终命名空间的方法,事件和数据。
最后加一个自己写的放大镜的插件`
(function($){$.fn.Fdj=function(){ $('#smallImg').on('mouseover', function() { $('#slider').show(); }) $('#smallImg').on('mouseout', function() { $('#slider').hide(); }) $('#smallImg').on('mousemove', function(e) { var x = e.clientX - $('#slider').width() / 2; var y = e.clientY - $('#slider').height() / 2; if(x <= 0) { x = 0 } if(x > $('#smallImg').width() - $('#slider').width()) { x = $('#smallImg').width() - $('#slider').width(); } if(y <= 0) { y = 0 } if(y > $('#smallImg').height() - $('#slider').height()) { y = $('#smallImg').height() - $('#slider').height(); } $('#slider').css({ 'left': x, 'top': y }) var X=x/$('#smallImg').width()*800 var Y=y/$('#smallImg').height()*800 $('#img').css({ left:-X, top:-Y }) }) } })(jQuery)
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of jQuery plug-in packaging steps. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

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



The default map on the iPhone is Maps, Apple's proprietary geolocation provider. Although the map is getting better, it doesn't work well outside the United States. It has nothing to offer compared to Google Maps. In this article, we discuss the feasible steps to use Google Maps to become the default map on your iPhone. How to Make Google Maps the Default Map in iPhone Setting Google Maps as the default map app on your phone is easier than you think. Follow the steps below – Prerequisite steps – You must have Gmail installed on your phone. Step 1 – Open the AppStore. Step 2 – Search for “Gmail”. Step 3 – Click next to Gmail app

When logging into iTunesStore using AppleID, this error saying "This AppleID has not been used in iTunesStore" may be thrown on the screen. There are no error messages to worry about, you can fix them by following these solution sets. Fix 1 – Change Shipping Address The main reason why this prompt appears in iTunes Store is that you don’t have the correct address in your AppleID profile. Step 1 – First, open iPhone Settings on your iPhone. Step 2 – AppleID should be on top of all other settings. So, open it. Step 3 – Once there, open the “Payment & Shipping” option. Step 4 – Verify your access using Face ID. step

WeChat is one of the social media platforms in China that continuously launches new versions to provide a better user experience. Upgrading WeChat to the latest version is very important to keep in touch with family and colleagues, to stay in touch with friends, and to keep abreast of the latest developments. 1. Understand the features and improvements of the latest version. It is very important to understand the features and improvements of the latest version before upgrading WeChat. For performance improvements and bug fixes, you can learn about the various new features brought by the new version by checking the update notes on the WeChat official website or app store. 2. Check the current WeChat version We need to check the WeChat version currently installed on the mobile phone before upgrading WeChat. Click to open the WeChat application "Me" and then select the menu "About" where you can see the current WeChat version number. 3. Open the app

Having issues with the Shazam app on iPhone? Shazam helps you find songs by listening to them. However, if Shazam isn't working properly or doesn't recognize the song, you'll have to troubleshoot it manually. Repairing the Shazam app won't take long. So, without wasting any more time, follow the steps below to resolve issues with Shazam app. Fix 1 – Disable Bold Text Feature Bold text on iPhone may be the reason why Shazam is not working properly. Step 1 – You can only do this from your iPhone settings. So, open it. Step 2 – Next, open the “Display & Brightness” settings there. Step 3 – If you find that “Bold Text” is enabled

Screenshot feature not working on your iPhone? Taking a screenshot is very easy as you just need to hold down the Volume Up button and the Power button at the same time to grab your phone screen. However, there are other ways to capture frames on the device. Fix 1 – Using Assistive Touch Take a screenshot using the Assistive Touch feature. Step 1 – Go to your phone settings. Step 2 – Next, tap to open Accessibility settings. Step 3 – Open Touch settings. Step 4 – Next, open the Assistive Touch settings. Step 5 – Turn on Assistive Touch on your phone. Step 6 – Open “Customize Top Menu” to access it. Step 7 – Now you just need to link any of these functions to your screen capture. So click on the first

Windows 11, as the latest operating system launched by Microsoft, is deeply loved by users. In the process of using Windows 11, sometimes we need to obtain system administrator rights in order to perform some operations that require permissions. Next, we will introduce in detail the steps to obtain system administrator rights in Windows 11. The first step is to click "Start Menu". You can see the Windows icon in the lower left corner. Click the icon to open the "Start Menu". In the second step, find and click "

If you don't have control over the zoom level in Safari, getting things done can be tricky. So if Safari looks zoomed out, that might be a problem for you. Here are a few ways you can fix this minor zoom issue in Safari. 1. Cursor magnification: Select "Display" > "Cursor magnification" in the Safari menu bar. This will make the cursor more visible on the screen, making it easier to control. 2. Move the mouse: This may sound simple, but sometimes just moving the mouse to another location on the screen may automatically return it to normal size. 3. Use Keyboard Shortcuts Fix 1 – Reset Zoom Level You can control the zoom level directly from the Safari browser. Step 1 – When you are in Safari

Is the clock app missing from your phone? The date and time will still appear on your iPhone's status bar. However, without the Clock app, you won’t be able to use world clock, stopwatch, alarm clock, and many other features. Therefore, fixing missing clock app should be at the top of your to-do list. These solutions can help you resolve this issue. Fix 1 – Place the Clock App If you mistakenly removed the Clock app from your home screen, you can put the Clock app back in its place. Step 1 – Unlock your iPhone and start swiping to the left until you reach the App Library page. Step 2 – Next, search for “clock” in the search box. Step 3 – When you see “Clock” below in the search results, press and hold it and
