jQuery 插件封装的方法

对于比较复杂的和提供了许多选项可定制的的插件,最好有一个当插件被调用的时候可以被拓展的默认设置(通过使用$.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'
});
posted @ 2018-03-07 18:05  糖糖部落  阅读(3519)  评论(0编辑  收藏  举报