標籤:
摘要
上篇文章簡單學習了js自調用方法。今天就趁熱打鐵,學一學怎麼編寫一個jquery外掛程式。
JQuery
參考地址:http://www.cnblogs.com/playerlife/archive/2012/05/11/2495269.html
通過JQuery.fn增加一個新的函數來編寫JQuery外掛程式,也可以說是在Jquery對象上面擴充一個新的方法。
程式碼片段:
jQuery.fn.myPluigin = function () { //code... };
似乎這樣就可以了,但有個問題,也許你的擴充的方法會和jquery中的方法產生衝突,所以這時候最好用一個 自執行的函數將其包裹起來,並且將JQuery作為參數傳進去。所以有了下面的代碼:
(function ($) { $.fn.myPluigin = function () { //code... }; })(jQuery);
通過這種方式,由於閉包的關係,所以和其它地方的並不會產生衝突。
一個簡單外掛程式
擷取頁面上div的最大寬度
<script> (function ($) { $.fn.maxWidth = function () { var max = 0; //this 指向的是jquery對象 this.each(function () { //this指向DOM元素,要取到這個dom元素,可以通過$(this) max = Math.max(max, $(this).width()); }); return max; }; })(jQuery); var maxWidth = $("div").maxWidth(); console.log(maxWidth);</script>
鏈式
為了使用jquery中鏈式開發的特性,所以在封裝外掛程式的時候,需要返回這個元素供鏈條上的下一個使用。
(function ($) { $.fn.Chain= function (type) { //this 指向的是jquery對象 return this.each(function () { var $this = $(this); if (type && type == "width") { $this.width($this.width()); } }); }; })(jQuery); $("div").Chain("width").css("color", "red");
因為該外掛程式返回了this,所以你可以繼續鏈式,比如 css()。如果你的外掛程式如果不是返回一個簡單值,你通常應該返回this。
預設值選項
在使用外掛程式的過程中,經常可以看到外掛程式有部分的預設值,我們只需傳入需要替換的參數即可,就可以對外掛程式進行配置。
(function ($) { $.fn.myAlert = function (options) { var settings = { "location": "top", "background-color": "red" }; console.log(‘default‘, settings); return this.each(function () { if (options) { $.extend(settings, options); console.log(‘extend‘, settings); }; }); }; })(jQuery); $("div").myAlert({ "location": "center" });
結果
在這個例子中,使用外掛程式後,預設的location被替換為center,而background-color保持原樣。這樣可以保證高度可配置醒,而不需要開發人員定義所有可能的選項了。
命名空間
命名空間的重要性,可以保證你的外掛程式不被其他外掛程式重寫,也能避免被頁面上其它代碼重寫。
注意
在任何情況下都不壓迫在一個外掛程式中為jQuery.fn增加多個方法。
(function ($) { $.fn.method1 = function () { }; $.fn.method2 = function () { }; .. $.fn.methodn = function () { };})(jQuery);
可以這樣,將方法放在一個對象裡面,然後根據不同的參數進行調用:
(function ($) { var methods = { method1: function (options) { }, method2: function () { }, }; $.fn.myMethod = function (method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else { //.... } } })(jQuery);
[Js/Jquery]jquery外掛程式開發