如何创建一个基础jQuery插件
如何創(chuàng)建一個(gè)基礎(chǔ)插件
How to Create a Basic Plugin
有時(shí)你想使一塊功能性的代碼在你代碼的任何地方有效.比如,也許你想調(diào)用jQuery對象的一個(gè)方法,對該對象進(jìn)行一系列的操作.可能你寫了一個(gè)真正有用的實(shí)用函數(shù),想它能夠輕易的移植到其他項(xiàng)目.在這種情況下,你可能想寫一個(gè)插件.
Sometimes you want to make a piece of functionality available throughout your code. For example, perhaps you want a single method you can call on a jQuery selection that perfroms a series of operations on the selection. Maybe you wrote a really useful utility function that you want to be able to move easily to other projects. In this case, you may want to write a plugin.
jQuery是如何工作的 101:jQuery 對象方法和實(shí)用方法
How jQuery Works 101:jQuery Object Methods and Utility Methods
在我們寫我們自己的插件之前, 我們必須先對jQuery如何工作有一些了解.請看看這段代碼:
Before we write our own plugins, we must first understand a little about how jQuery works.Take a look at this code:
$("a").css("color", "red"); 這是一段簡單的jQuery代碼,但是你知道在幕后發(fā)生了什么嗎?每當(dāng)你使用 $ 函數(shù)來選擇元素,他會返回一個(gè)jQuery對象.這個(gè)對象包含了所有你以前使用過的方法(.css(), .click() 等等)和適合你的選擇器的所有元素.jQuery對象從 $.fn 對象獲取這些這些方法.這個(gè)對象包含了所有jQuery對象的方法,如果我們想寫我們自己的方法,它也必須包含在內(nèi).
This is some pretty basic jQuery code, but do you know what's happning behind the scenes?Whenever you use the $ function to select elements, it returns a jQuery object. This object contains all of the methods you've been using(.css(), .click(), etc.)and all of the elements that fit your selector. The jQuery object gets these methods from the $.fn object. This object contains all of the jQuery object methods, and if we want to write our own methods, it will need to contain those as well.
此外jQuery實(shí)用函數(shù) $.trim() 用來刪除用戶輸入前后的空白符.實(shí)用方法是直接屬于 $ 函數(shù)本身的.當(dāng)jQuery API沒有對你檢索到的DOM元素組實(shí)現(xiàn)預(yù)期功能時(shí),你也許有時(shí)想寫一個(gè)實(shí)用函數(shù)插件對其進(jìn)行擴(kuò)展.
Additionally the jQuery utility method $.trim() it used above to remove any leading or trailing empty space characters from the user input. Utility methods are functions that reside directly in the $ function itself. You may occasionally want to write a utility method plugin when your extension to the jQuery API does not have to do something to a set of DOM elements you've retrieved.
基本插件創(chuàng)作
Basic Plugin Authoring
比如說我們想創(chuàng)建一個(gè)使檢索到的元素變綠的插件.我們要做的就是在 $.fn 中添加一個(gè)名為 greenify 的函數(shù),它會像其他jQuery對象函數(shù)一樣有效.
Let's say we want to create a plugin that makes test within a set of retrieved elements green. All we have to do is add a function called greenify to $.fn and it will be available just like any other jQuery object method.
$.fn.greenify = function(){
this.css("color", "green");
}
$("a").greenify();
注意使用 .css() 和其他類似方法時(shí),我們用 this 而不是 $(this).這是因?yàn)槲覀兊?greenify 函數(shù)和 .css() 是同一個(gè)對象的一部分.
Notice that use .css(), another method, we use this, not $(this). This is because our greenify function is a part of the same object as .css().
連貫性
Chaining
它工作了,但是實(shí)際上我們會有幾件事情要做,jQuery的特性之一就是連貫性,當(dāng)你鏈接了四到五個(gè)動作到一個(gè)選擇器.這是通過所有的 jQuery 對象方法再次返回源 jQuery 對象來實(shí)現(xiàn)的(這里有一些例外: 無參數(shù)調(diào)用 .width() 返回選中元素的寬度, 它是沒有連貫性的).使我們的插件方法具有連貫性需要一行代碼:
This works, but there's a couple of things we need to do for our plugin to survive in the reeal world. One of jQuery's features is chaining, when you link five or six actions onto one selector. This is accomplished by having all jQuery object methods return the original jQuery object again(there are few exceptions: .width() called without parameters return the width of the selected element, and is not chainable). Making our plugin method chainable takes one line of code:
$.fn.greenify = function(){this.css("color", "green");return this;
}
$("a").greenify().addClass("greenified");
值得注意的是連貫性的概念在類似 $.trim() 的 jQuery 實(shí)用函數(shù)上不適用.
Note that the notion of chaining is not applicable to jQuery utility methods like $.trim().
保護(hù)$別名和添加范圍
Protecting $ Alias and Adding Scope
變量$在JavaScript庫中非常受歡迎,如果你在使用jQuery的同時(shí)使用其他的庫,你應(yīng)使用jQuery.noConflict()來使jQuery不使用$.然而,假設(shè)$是jQuery函數(shù)的別名將損壞我們的插件.我們需要將我們所有的代碼放進(jìn)一個(gè)立即調(diào)用函數(shù)表達(dá)式里面, 然后傳遞函數(shù)jQuery,命名為參數(shù)$:
The $ variable is very popular among JavaScript libraries, and if you're using another library with jQuery, you will have make jQuery not use the $ with jQuery.noConflict(). However, this will break our plugin since it is written with the assumption that $ is an alias to the jQuery function. To work well with other plugins, and still use the jQuery $ alias, we need to put all of our code inside of an Immediately Invoked Function Expression, and then pass the function jQuery, and name the parameter $:
(funtion($){$.fn.greenify = function(){this.css("color", "green");return this;}$.ltrim = function(str){return str.replace(/^\s+/, "");}$.rtrim = function(str){return str.replace(/\s+$/, "");}
}(jQuery));
并且,立即調(diào)用函數(shù)表達(dá)式的主要作用是允許我們擁有自己的私有變量.假設(shè)我們想添加一個(gè)不同的顏色,而且我們想將它保存在一個(gè)變量里面.
in addition, the primary purpose of an Immediately Invoked Function is to allow us to have our private variables. Pretend we want a different color, and we want to store it in a variable.
(function($){var shade = "#556b2f";$.fn.greenify = function(){this.css("color", shade);return this;}
}(jQuery)); Minimizing Plugin Footprint
好的慣例是寫一個(gè)插件只占用 $.fn 的一個(gè)接口,這段代碼可能導(dǎo)致你的插件被其他的插件覆蓋,也可能導(dǎo)致你的插件覆蓋了其他插件,換句話說,這是段糟糕的代碼:
It's good practice when writing plugins to only take up one slot within $.fn. This reduces both the chance that your plugin will be overridden, and the chance that your plugin will override other plugins. In other words, this is bad:
(function($){$.fn.openpopup = function(){//open popup code.}$.fn.closepopup = function(){//close popup code.}
}(jQuery)); 使用單接口和使用參數(shù)來控制單接口執(zhí)行什么樣的行動將會好得多
It would be much better to have one slot, and use parameters to control what action that one slot performs.
(function( $ ) {$.fn.popup = function( action ) {if ( action === "open") {// Open popup code.}if ( action === "close" ) {// Close popup code.}};
}( jQuery )); 使用 each() 方法
Using the each() Method
你的典型的jQuery對象可能包含任意數(shù)量的DOM元素,這也是為什么經(jīng)常把jQuery對象稱為集合的原因.如果你想對特定的元素進(jìn)行一些操作(例如:讀取屬性, 計(jì)算特定位置),那么你需要使用 .each() 來遍歷這些元素.
Your typical jQuery object will contain references to any number of DOM elements, and that's why jQuery objects are often referred to as collections. If you want to do any manipulating with specific elements (e.g. getting a data attribute, calculating specific positions) then you need to use .each() to loop through the elements.
$.fn.myNewPlugin = function(){return this.each(function(){//Do something to each element here.});
} 注意我們返回 .each() 代替返回 this. 因?yàn)?.each() 已經(jīng)是具有連貫性的,它的返回值是 this.在我們曾經(jīng)做過的事中,到目前為止,這是一個(gè)維護(hù)可連續(xù)性更好的辦法.
Notice that we return the results of .each() instead of returning this. Since .each() is already chainable, it returns this, which we then return. This is a better way to maintain chainability than what we've been doing so far.
接受選項(xiàng)
Accepting Options
當(dāng)你的插件越來越復(fù)雜,好的主意是通過接受一些選項(xiàng)來使你的插件可定制.最簡單的做到這一點(diǎn)的辦法是一個(gè)字面對象,特別是有很多的選項(xiàng).讓我們修改我們的greenify插件以接受一些選項(xiàng).
As your plugins get more and more complex, it's a good idea to make your plugin customizable by accepting options. The easiest way do this, especially if there are lots of options, is with an object literal. Let's change our greenify plugin to accept some options.
(function($){$.fn.greenify = function(options){//This is the easiest way to have default optionvar settings = $.extend({//These are the defaults.color: "#55b62f",backgroundColor: "white"}, options);//Greenify the collection based on the settingsreturn this.css({color: setting.color,backgroundColor: setting.backgroundColor});};
}(jQuery));//Example usage:$("div").greenify({color: "orange"
}); color 的缺省值 #556b2f 被 $.extend() 覆蓋為 orange.
The default value for color of #556b2f gets overridden by $.extend() to be orange.
把它們放在一起
Putting It Together
這里是一個(gè)使用了一些我們已經(jīng)討論過的技巧的小插件例子:
Here's an example of a small plugin using some of the techniques we've discussed:
(function($){$.fn.showLinkLocation = function(){return this.filter("a").each(function(){$(this).append(" (" + $(this).attr("href") + ")");});};
}(jQuery));//Example usage:$("a").showLinkLocation(); 這個(gè)易用的插件遍歷集合中所有的鏈接然后把href屬性放在括弧中添加在元素后面.
This handy plugin goes through all anchors in the collection and appends the href attribute in brackets.
我們的插件可以通過以下代碼優(yōu)化:
Our plugin can be optimized though:
(function($){$.fn.showLinkLocation = function(){return this.filter("a").append(function(){return " (" + this.href + ")";})};
}(jQuery)); 我們使用的是 .append() 方法的接受回調(diào)函數(shù)的能力,返回值將決定集合中的每個(gè)元素的尾部添加什么.注意我們不是使用 .attr() 方法來檢索href屬性,因?yàn)樵腄OM API給了我們適當(dāng)命名的href屬性方便使用.
We're using the .append() method's capability to accept a callback, and the return value of that callback will determine what is appended to each element in the collection. Notice also that we're not using the .attr() method to retrieve the href attribute, because the native DOM API gives us easy access with the aptly named href property.
轉(zhuǎn)載于:https://www.cnblogs.com/brokenjar/p/basic-plugin-creation.html
總結(jié)
以上是生活随笔為你收集整理的如何创建一个基础jQuery插件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于 WPF + Modern UI 的
- 下一篇: 幸运粒子换哪个宠物