search
HomeWeb Front-endJS TutorialjQuery plug-in development tutorial

jQuery plug-in development tutorial

May 11, 2020 am 09:20 AM
jqueryjs

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 a new function attribute to jQuery.fn. The name of the object attribute added here is the name of your plug-in. :

The code is as follows:

jQuery.fn.myPlugin = function(){
  //你自己的插件代码
};

Where is the $ symbol that users like so much? It still exists, but in order to avoid conflicts with other JavaScript libraries, it is best to pass jQuery to a self-executing closed program, where jQuery is mapped to the $ sign, so that the $ sign is not overwritten by other libraries.

The code is as follows:

(function ($) {
    $.fn.myPlugin = function () {
        //你自己的插件代码
    };
})(jQuery);

In this closed program, we can use the $ symbol without restriction to represent jQuery functions.

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 that we understand the basics of jQuery plug-ins, let us write a plug-in to do Issues.

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 = $('div').maxHeight(); //返回高度最大的div元素的高度

This is a simple plug-in that uses .height() to return the height of the div element with the largest height on the page.

4. Maintain Chainability

Many times, the intention of a plug-in is just 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);
$('div').lockDimensions('width').CSS('color', 'red');

Since the plugin returns this keyword, it maintains chainability, so that elements collected by jQuery can continue to be controlled by jQuery methods such as .css. Therefore, if your plugin does not return an intrinsic value, you should always return the this keyword within its scope. Additionally, you might deduce that parameters passed to a plugin will be passed within the plugin's scope. Therefore, in the previous example, the string 'width' becomes a type parameter of the plugin.

5. Default values ​​and options

For more complex plug-ins that provide many customizable options, it is best to have one that can be used when the plug-in is called The default settings are extended (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);
$('div').tooltip({
    'location': 'left'
});

In this example, when calling the tooltip plug-in, the location option in the default settings is overwritten, and the background-color option remains at its default value, so the setting that is finally called The value is:

The code is as follows:

{
    'location': 'left',
    'background-color': 'blue'
}

This is a very flexible way to provide a highly configurable plug-in without requiring the developer to define all available options.

6. Namespace

Correctly naming your plug-in is a very important part of plug-in development. With the right namespace, you can guarantee that your plugin will have a very low chance of being overwritten by other plugins or other code on the same page. Namespaces also make your life as a plugin developer easier because it helps you better keep track of your methods, events, and data.

7. Plug-in methods

In any case, a single plug-in should not have multiple namespaces in the jQuery.fnjQuery.fn object.

The code is as follows:

(function ($) {
    $.fn.tooltip = function (options) {
        // this
    };
    $.fn.tooltipShow = function () {
        // is
    };
    $.fn.tooltipHide = function () {
        // bad
    };
    $.fn.tooltipUpdate = function (content) {
        // !!!
    };
})(jQuery);

This is discouraged because $.fn clutters the $.fn namespace. To solve this problem, you should collect all the plugin's methods in the object text and call them by passing the string name of the method to the plugin.

The code is as follows:

(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方法
$('div').tooltip();
//调用init方法
$('div').tooltip({
    foo: 'bar'
});
// 调用hide方法
$('div').tooltip('hide');
//调用Update方法
$('div').tooltip('update', 'This is the new tooltip content!');

This type of plug-in architecture allows you to encapsulate all methods in the parent package by passing the string name of the method and additional parameters required by this method. Call them. This type of encapsulation and architecture is standard in the jQuery plug-in community, and it is used by countless plug-ins, including plug-ins and widgets in jQuery UI.

8. Events

A little-known function of the bind method is to allow binding of event namespaces. If your plugin binds an event, a good practice is to namespace this event. This way, when you unbind, you won't interfere with other events of the same type that may already be bound. You can do this by appending the namespace to the event you need to bind via '.'.

code show as below:

(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 = $(&#39;<div />&#39;, {
                        text: $this.attr(&#39;title&#39;)
                    });
                // If the plugin hasn&#39;t been initialized yet
                if (!data) {
                    /*
                     Do more setup stuff here
                     */
                    $(this).data(&#39;tooltip&#39;, {
                        target: $this,
                        tooltip: tooltip
                    });
                }
            });
        },
        destroy: function () {
            return this.each(function () {
                var $this = $(this),
                    data = $this.data(&#39;tooltip&#39;);
                // Namespacing FTW
                $(window).unbind(&#39;.tooltip&#39;);
                data.tooltip.remove();
                $this.removeData(&#39;tooltip&#39;);
            })
        },
        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 === &#39;object&#39; || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error(&#39;Method &#39; + method + &#39; does not exist on jQuery.tooltip&#39;);
        }
    };
})(jQuery);

将数据通过命名空间封装在一个对象中,可以更容易的从一个集中的位置读取所有插件的属性。

十、总结和最佳做法

编写jQuery插件允许你做出库,将最有用的功能集成到可重用的代码,可以节省开发者的时间,使开发更高效。 开发jQuery插件时,要牢记:

1.始终包裹在一个封闭的插件:

代码如下:

(function($) {
/* plugin goes here */
})(jQuery);

2.不要冗余包裹this关键字在插件的功能范围内

3.除非插件返回特定值,否则总是返回this关键字来维持chainability 。

4.传递一个可拓展的默认对象参数而不是大量的参数给插件。

5.不要在一个插件中多次命名不同方法。

3.始终命名空间的方法,事件和数据。

推荐教程:《JS教程

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

Statement
This article is reproduced at:cnblogs. If there is any infringement, please contact admin@php.cn delete
JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

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 Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools