Standard writing method for jQuery plug-in development
Preface
Nowadays, jquery is almost indispensable for web development. Even the VS artifact has built jquery and ui into web projects since the 2010 version. As for the benefits of using jquery, I won’t go into details here, everyone who has used it knows it. Today we will discuss the plug-in mechanism of jquery. jquery has thousands of third-party plug-ins. Sometimes we have written an independent function and want to combine it with jquery. We can use jquery chain call. This requires Extend jquery and write it in the form of a plug-in. For example, the following is a demo of simply extending the Jquery object:
//sample:扩展jquery对象的方法,bold()用于加粗字体。 (function ($) { $.fn.extend({ "bold": function () { ///<summary> /// 加粗字体 ///</summary> return this.css({ fontWeight: "bold" }); } }); })(jQuery);
Calling method:
This is a very simple Extension. Next we analyze the above code step by step.
1. jquery’s plug-in mechanism
In order to facilitate users to create plug-ins, jquery provides jQuery.extend() and jQuery.fn.extend() methods.
1. The jQuery.extend() method has an overload.
jQuery.extend(object), one parameter is used to extend the jQuery class itself, which is used to add new functions to the jQuery class/namespace, or static methods, such as jQuery's built-in Ajax methods are all called using jQuery.ajax(), which is a bit like the "class name. method name" static method calling method. Let’s also write an example of jQuery.extend(object):
//扩展jQuery对象本身 jQuery.extend({ "minValue": function (a, b) { ///<summary> /// 比较两个值,返回最小值 ///</summary> return a < b ? a : b; }, "maxValue": function (a, b) { ///<summary> /// 比较两个值,返回最大值 ///</summary> return a > b ? a : b; } }); //调用 var i = 100; j = 101; var min_v = $.minValue(i, j); // min_v 等于 100 var max_v = $.maxValue(i, j); // max_v 等于 101
Overloaded version: jQuery.extend([deep], target, object1, [objectN])
Extend an object with one or more other objects and return The object being extended.
If no target is specified, the jQuery namespace itself will be expanded. This helps plugin authors add new methods to jQuery.
If the first parameter is set to true, jQuery returns a deep copy, recursively copying any objects found. Otherwise, the copy will share the structure with the original object.
Undefined properties will not be copied, however properties inherited from the object's prototype will be copied.
Parameters
deep: Optional. If set to true, merge recursively.
target: The object to be modified.
object1: The object to be merged into the first object.
objectN: Optional. The object to be merged into the first object.
Example 1:
Merge settings and options, modify and return settings.
var settings = { validate: false, limit: 5, name: "foo" }; var options = { validate: true, name: "bar" }; jQuery.extend(settings, options);
Result: <br/>
settings == { validate: true, limit: 5, name: "bar" }
Example 2:
Merge defaults and options , do not modify defaults.
var empty = {}; var defaults = { validate: false, limit: 5, name: "foo" }; var options = { validate: true, name: "bar" }; var settings = jQuery.extend(empty, defaults, options); 结果: settings == { validate: true, limit: 5, name: "bar" } empty == { validate: true, limit: 5, name: "bar" }
<br/>This overloaded method is generally used to override the default parameters of the plug-in with custom plug-in parameters when writing plug-ins.
jQuery.fn.extend(object) extends the jQuery element set to provide new methods (usually used to make plug-ins).
First of all, let’s take a look at what fn is. Looking at the jQuery code, it's not hard to find.
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {.....};
};
Original jQuery .fn = jQuery.prototype, which is the prototype of the jQuery object. The jQuery.fn.extend() method is the prototype method of extending the jQuery object. We know that extending the method on the prototype is equivalent to adding a "member method" to the object. The "member method" of the class can only be called by the object of the class, so use the jQuery.fn.extend(object) extended method, an instance of the jQuery class You can use this "member function". The jQuery.fn.extend(object) and jQuery.extend(object) methods must be distinguished.
2. Self-executing anonymous function/closure
1. 什么是自执行的匿名函数?
它是指形如这样的函数: (function {// code})();
2. 疑问 为什么(function {// code})();可以被执行, 而function {// code}();却会报错?
3. 分析
(1). 首先, 要清楚两者的区别: (function {// code})是表达式, function {// code}是函数声明.
(2). 其次, js"预编译"的特点: js在"预编译"阶段, 会解释函数声明, 但却会忽略表式.
(3). 当js执行到function() {//code}();时, 由于function() {//code}在"预编译"阶段已经被解释过, js会跳过function(){//code}, 试图去执行();, 故会报错;
当js执行到(function {// code})();时, 由于(function {// code})是表达式, js会去对它求解得到返回值, 由于返回值是一 个函数, 故而遇到();时, 便会被执行.
另外, 函数转换为表达式的方法并不一定要靠分组操作符(),我们还可以用void操作符,~操作符,!操作符……
例如:
bootstrap 框架中的插件写法:
!function($){
//do something;
}(jQuery);
和
(function($){
//do something;
})(jQuery); 是一回事。
匿名函数最大的用途是创建闭包(这是JavaScript语言的特性之一),并且还可以构建命名空间,以减少全局变量的使用。
例如:
var a=1;
(function()(){
var a=100;
})();
alert(a); //弹出 1
更多 闭包和匿名函数 可查看 Javascript的匿名函数与自执行 这篇文章。
三、一步一步封装JQuery插件
接下来我们一起来写个高亮的jqury插件
1.定一个闭包区域,防止插件"污染"
//闭包限定命名空间(function ($) { })(window.jQuery);
2.jQuery.fn.extend(object)扩展jquery 方法,制作插件
//闭包限定命名空间(function ($) { $.fn.extend({ "highLight":function(options){ //do something } }); })(window.jQuery);
//闭包限定命名空间(function ($) { $.fn.extend({ "highLight": function (options) { var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数 this.each(function () { //这里的this 就是 jQuery对象 //遍历所有的要高亮的dom,当调用 highLight()插件的是一个集合的时候。 var $this = $(this); //获取当前dom 的 jQuery对象,这里的this是当前循环的dom //根据参数来设置 dom的样式 $this.css({ backgroundColor: opts.background, color: opts.foreground }); }); } }); //默认参数 var defaluts = { foreground: 'red', background: 'yellow' }; })(window.jQuery);
到这一步,高亮插件基本功能已经具备了。调用代码如下:
$(function () { $("p").highLight(); //调用自定义 高亮插件});
这里只能 直接调用,不能链式调用。我们知道jQuey是可以链式调用的,就是可以在一个jQuery对象上调用多个方法,如:
$('#id').css({marginTop:'100px'}).addAttr("title","测试“);
但是我们上面的插件,就不能这样链式调用了。比如:$("p").highLight().css({marginTop:'100px'}); //将会报找不到css方法,原因在与我的自定义插件在完成功能后,没有将 jQuery对象给返回出来。接下来,return jQuery对象,让我们的插件也支持链式调用。(其实很简单,就是执行完我们插件代码的时候将jQuery对像return 出来,和上面的代码没啥区别)
1 //闭包限定命名空间 2 (function ($) { 3 $.fn.extend({ 4 "highLight": function (options) { 5 var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数 6 return this.each(function () { //这里的this 就是 jQuery对象。这里return 为了支持链式调用 7 //遍历所有的要高亮的dom,当调用 highLight()插件的是一个集合的时候。 8 var $this = $(this); //获取当前dom 的 jQuery对象,这里的this是当前循环的dom 9 //根据参数来设置 dom的样式10 $this.css({11 backgroundColor: opts.background,12 color: opts.foreground13 });14 });15 16 }17 });18 //默认参数19 var defaluts = {20 foreground: 'red',21 background: 'yellow'22 };23 })(window.jQuery);
View Code
4.暴露公共方法 给别人来扩展你的插件(如果有需求的话)
比如的高亮插件有一个format方法来格式话高亮文本,则我们可将它写成公共的,暴露给插件使用者,不同的使用着根据自己的需求来重写该format方法,从而是高亮文本可以呈现不同的格式。
//公共的格式化 方法. 默认是加粗,用户可以通过覆盖该方法达到不同的格式化效果。 $.fn.highLight.format = function (str) { return "<strong>" + str + "</strong>"; }
5.插件私有方法
有些时候,我们的插件需要一些私有方法,不能被外界访问。例如 我们插件里面需要有个方法 来检测用户调用插件时传入的参数是否符合规范。
6.其他的一些设置,如:为你的插件加入元数据插件的支持将使其变得更强大。
完整的高亮插件代码如下:
//闭包限定命名空间(function ($) { $.fn.extend({ "highLight": function (options) { //检测用户传进来的参数是否合法 if (!isValid(options)) return this; var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数 return this.each(function () { //这里的this 就是 jQuery对象。这里return 为了支持链式调用 //遍历所有的要高亮的dom,当调用 highLight()插件的是一个集合的时候。 var $this = $(this); //获取当前dom 的 jQuery对象,这里的this是当前循环的dom //根据参数来设置 dom的样式 $this.css({ backgroundColor: opts.background, color: opts.foreground }); //格式化高亮文本 var markup = $this.html(); markup = $.fn.highLight.format(markup); $this.html(markup); }); } }); //默认参数 var defaluts = { foreground: 'red', background: 'yellow' }; //公共的格式化 方法. 默认是加粗,用户可以通过覆盖该方法达到不同的格式化效果。 $.fn.highLight.format = function (str) { return "<strong>" + str + "</strong>"; } //私有方法,检测参数是否合法 function isValid(options) { return !options || (options && typeof options === "object") ? true : false; } })(window.jQuery);
//调用 //调用者覆盖 插件暴露的共公方法 $.fn.highLight.format = function (txt) { return "<em>" + txt + "</em>" } $(function () { $("p").highLight({ foreground: 'orange', background: '#ccc' }); //调用自定义 高亮插件 });
The above is the detailed content of Standard writing method for jQuery plug-in development. 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

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

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

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute
