Jquery 插件开发全解析
http://www.cnblogs.com/libin-1/p/5944611.html
//一: 定义全局变量,三种方式
//(1)定义单个全局变量
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);
};
//(2)使用 extend 扩展 全局变量
jQuery.extend({
newfoo:function(){
alert('This is extend variable.');
},
newbar:function(param){
alert('This is extend parameter, which is '+ param);
}
});
//(3)使用命名空间定义变量,避免和其他全局变量冲突
jQuery.myPlugin = {
foo:function(){
alert('This is my foo.');
},
bar:function(param){
alert('This is my param, which is '+param);
}
};
//二:定义新插件,两种形式
//(1)首先创建一个闭包,使用extend
(function($){
$.extend({
pluginName:function(option,callback){
//Our plugin implementation code goes here
}
});
})(jQuery);
//(2)首先创建一个闭包, 使用 $.fn.
(function($){
$.fn.hilight = function(options){
//Extend our default options with those provided
//Note that the first arg to extend is an empty object
//this is to keep from overriding our "defaults" object
var opts = $.extend({},$.fn.hilight.defaults,options);
// Our plugin implementation code goes here
return this.each(function(){
var $this = $(this);
$this.css({
background:opts.background,
color:opts.foreground
});
var markup = $this.html();
//call our format function
markup = $.fn.hilight.format(markup);
$this.html(markup);
});
};
//plugin defaults ---- added as a property on our plugin function
$.fn.hilight.defaults = {
foreground : 'red',
background : 'yellow'
};
// define our format function
$.fn.hilight.format = function(txt){
return '<strong>'+txt+'</strong>';
};
})(jQuery);