标签:
jQuery插件的开发包括两种:
一种是类级别的插件开发,即给jQuery添加新的全局函数,相当于给jQuery类本身添加方法。jQuery的全局函数就是属于jQuery命名空间的函数,另一种是对象级别的插件开发,即给jQuery对象添加方法。下面就两种函数的开发做详细的说明。
类级别的插件开发
自定义全局函数
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‘);
使用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 +‘".‘);
}
});
对象级别的插件开发
对象级别的插件开发需要如下的两种形式:
形式1:
(function($){
$.fn.extend({
pluginName:function(opt,callback){
// Our plugin implementation code goes here.
}
})
})(jQuery);
形式2:
(function($) {
$.fn.pluginName = function() {
// Our plugin implementation code goes here.
};
})(jQuery);
上面定义了一个jQuery函数,形参是$,函数定义完成之后,把jQuery这个实参传递进去.立即调用执行。这样的好处是,我们在写jQuery插件时,也可以使用$这个别名,而不会与prototype引起冲突.
调用样例如下
$(‘#myDiv‘).hilight();
接受options参数以控制插件的行为
// 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‘
});
参考资料
标签:
原文地址:http://www.cnblogs.com/mascott/p/4744868.html