码迷,mamicode.com
首页 > Web开发 > 详细

[整理] jQuery插件开发

时间:2014-07-07 18:11:40      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:style   blog   java   color   使用   cti   

1、类级别的插件开发

类级别的插件开发,可似为给jQuery类添加方法,调用方式:$.你的方法(),如:$.ajax() 函数。

 

1.1、给jQuery类添加方法

$.alertMsg = function(msg){
	alert("alertMsg : " + msg);	
};
// 调用
// $.alertMsg("hello");

 

1.2、给jQuery类添加带命名空间的方法

$.myPlugin = {
	alertMsg : function(msg){
		alert("myPlugin.alertMsg : " + msg);	
	},	
};
// 调用
// $.myPlugin.alertMsg("hello");

 

1.3、使用 jQuery.extend 给jQuery类添加方法

$.extend({
	alertMsg2 : function(msg){
		alert("alertMsg2 : " + msg);	
	},
	// 调用
	// $.alertMsg2("hello");
	
	myPlugin2 : {
		alertMsg : function(msg){
			alert("myPlugin2.alertMsg : " + msg);	
		},	
	},
	// 调用
	// $.myPlugin2.myPlugin2("hello");
});

 

2、对象级别的插件开发

对象级别的插件开发,可似为给jQuery对象添加方法,调用方式:$(对象).你的方法(),如:$("body").css() 函数。

 

2.1、给jQuery对象添加方法

$.fn.alertText = function(msg){
	alert("alertText : " + this.text() + " , " + msg);
};
// 调用
// $(elem).alertText("hello");

 

2.2、给jQuery对象添加带名命空间的方法

$.fn.myPlugin = {
	alertText : function(msg){
		// this 为 myPlugin 对象,要获取事件源,使用event.target
		alert("myPlugin.alertText : " + $(event.target).text() + " , " + msg);
	},
};
// 调用
// $(elem).myPlugin.alertText("hello");

$.fn.myPlugin2 = function(method){
	var methods = {
		init : function(){
			alert("myPlugin2.init");
		},	
		alertText : function(msg){
			alert("myPlugin2.alertText : " + this.text() + " , " + msg);	
		},
	};
	
	if(methods[method]){
		return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));	
	}else{
		return methods.init();	
	} 
};
// 调用
// $(elem).myPlugin2(); // $(elem).myPlugin2("init");
// $(elem).myPlugin2("alertText", "hello");

 

2.3、 使用 jQuery.fn.extend 给jQuery对象添加方法

$.fn.extend({
	alertText2 : function(msg){
		alert("alertText2 : " + this.text() + " , " + msg);
	},
	// 调用
	// $(elem).alertText2("hello");
	
	myPlugin3 : {
		alertText : function(msg){
			// this 为 myPlugin 对象,要获取事件源,使用event.target
			alert("myPlugin3.alertText : " + $(event.target).text() + " , " + msg);
		},
	},
	// 调用
	// $(elem).myPlugin3.alertText("hello");
	
	myPlugin4 : function(method){
		var methods = {
			init : function(){
				alert("myPlugin4.init");
			},	
			alertText : function(msg){
				alert("myPlugin4.alertText : " + this.text() + " , " + msg);	
			},
		};
		
		if(methods[method]){
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));	
		}else{
			return methods.init();	
		}
	}
	// 调用
	// $(elem).myPlugin4(); // $(elem).myPlugin4("init");
	// $(elem).myPlugin4("alertText", "hello");
});

 

[整理] jQuery插件开发,布布扣,bubuko.com

[整理] jQuery插件开发

标签:style   blog   java   color   使用   cti   

原文地址:http://www.cnblogs.com/withme/p/3813584.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!