jQuery插件开发一般通过两种框架方式:
一种是在jQuery对象上直接定义新成员,形成插件;
另一种是封装完整的插件代码,然后将jQeury作为参数自身调用,达到给jQuery对象扩展功能目的,形成插件。
其实两种方式都是给jQeury对象扩展成员来实现插件功能的,所以本质上功能相同。下面逐一分析两种架构。1、在jQuery对象上直接定义新成员
这种开发方式可以理解为给jQuery类添加静态方法。典型的例子就是$.AJAX()这个函数,将函数定义于jQuery的命名空间中。可以采用如下几种形式进行扩展:
1.1、添加一个新的全局函数
添加一个全局函数,我们只需如下定义:
- jQuery.foo
= function() { - alert('This
is a test. This is only a test.'); - };
添加多个全局函数,可采用如下定义:
- jQuery.foo
= function() { - alert('This
is a test. This is only a test.'); - };
- jQuery.bar
= function(param) { - alert('This
function takes a parameter, which is "' + param + '".'); - };
- 调用时和一个函数的一样的:jQuery.foo();jQuery.bar();或者$.foo();$.bar('bar');
1.3、使用jQuery.extend(object)
- jQuery.extend({
- foo:
function() { - alert('This
is a test. This is only a test.'); - },
- bar:
function(param) { - alert('This
function takes a parameter, which is "' + param +'".'); - }
- });
- jQuery.myPlugin
= { - foo:function()
{ - alert('This
is a test. This is only a test.'); - },
- bar:function(param)
{ - alert('This
function takes a parameter, which is "' + param + '".'); - }
- };
- 采用命名空间的函数仍然是全局函数,调用时采用的方法:
- $.myPlugin.foo();
- $.myPlugin.bar('baz');
形式1:
- (function($){
- $.fn.extend({
- pluginName:function(opt,callback){
-
// Our plugin implementation code goes here. - }
- })
- })(jQuery);
- (function($)
{ - $.fn.pluginName
= function() { -
// Our plugin implementation code goes here. - };
- })(jQuery);
上面定义了一个jQuery函数,形参是$,函数定义完成之后,把jQuery这个实参传递进去.立即调用执行。这样的好处是,我们在写jQuery插件时,也可以使用$这个别名,而不会与prototype引起冲突.
3、定义可通过selector选择器调用的插件函数
- $.fn.hilight
= function() { -
// Our plugin implementation code goes here. - };
- 我们的插件通过这样被调用:
- $('#myDiv').hilight();
4、多参数定义
- //
plugin definition - $.fn.hilight
= function(options) { -
var defaults = { -
foreground: 'red', -
background: 'yellow' -
}; -
// Extend our default options with those provided. -
var opts = $.extend(defaults, options); -
// Our plugin implementation code goes here. - };
- 我们的插件可以这样被调用:
- $('#myDiv').hilight({
-
foreground: 'blue' - });
4.1、对象方式定义插件参数
-
$.fn.hilight = function(options) { -
var opts = $.extend({}, $.fn.hilight.defaults, options); -
// 代码内容 - };
- $.fn.hilight.defaults = {
-
foreground: 'red', -
background: 'yellow' -
};
//这个只需要调用一次,且不一定要在ready块中调用
$.fn.hilight.defaults.foreground = 'blue';
接下来我们可以像这样使用插件的方法,结果它设置蓝色的前景色:
$('#myDiv').hilight();