對於比較復雜的和提供了許多選項可定制的的插件,最好有一個當插件被調用的時候可以被拓展的默認設置(通過使用$.extend)。 因此,相對於調用一個有大量參數的插件,你可以調用一個對象參數,包含你了你想覆寫的設置。
(function ($) { $.fn.tooltip = function (options) { //創建一些默認值,拓展任何被提供的選項 var settings = $.extend({ 'location': 'top', 'background-color': 'blue' }, options); return this.each(function () { // Tooltip插件代碼 }); }; })(jQuery); $('div').tooltip({ 'location': 'left' });
很多時候,一個插件的意圖僅僅是以某種方式修改收集的元素,並把它們傳遞給鏈中的下一個方法。 這是jQuery的設計之美,是jQuery如此受歡迎的原因之一。 因此,要保持一個插件的chainability,你必須確保你的插件返回this關鍵字。
(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');
在任何情況下,一個單獨的插件不應該在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方法 $('div').tooltip(); //調用init方法 $('div').tooltip({ foo: 'bar' }); // 調用hide方法 $(‘div').tooltip(‘hide'); //調用Update方法 $(‘div').tooltip(‘update', ‘This is the new tooltip content!');
參考文章:http://www.jb51.net/article/97493.htm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
(
function
($) {
$.fn.tooltip =
function
(options) {
//創建一些默認值,拓展任何被提供的選項
var
settings = $.extend({
'location'
:
'top'
,
'background-color'
:
'blue'
}, options);
return
this
.each(
function
() {
// Tooltip插件代碼
});
};
})(jQuery);
$(
'div'
).tooltip({
'location'
:
'left'
});
|