JQ 插件的理解

jQuery为开发插件提拱了两个方法,分别是:
jQuery.fn.extend();
jQuery.extend();
PS:jQuery.fn 等价 jQuery.prototype。

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
</head>
<body>
<script type="text/javascript" src="jquery-1.10.1.min.js"></script>
<script>
$.extend({
	//多个方法,使用 , 隔开
	min: function(a, b) { return a < b ? a : b; },
	max: function(a, b) { return a > b ? a : b; }
});
var minVal = $.min(2,3);
var maxVal = $.max(4,5);
console.info(minVal);//2
console.info(maxVal);//5
</script>
</body>
</html>

 效果图:

 

$("#btn")为一个jQuery实例,当它调用成员方法 showBtnVal 后,便实现了扩展,每次被点击时它都向控制台输出当前的内容。

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
</head>
<body>
<button value="阅谁问君诵,水落清香浮。" id="btn">按钮</button>
<script type="text/javascript" src="jquery-1.10.1.min.js"></script>
<script>
$.fn.extend({
	showBtnVal:function() {
		//this 指当前的参数
		$(this).click(function(){
			console.info($(this).val());
		});
	}
});
$("#btn").showBtnVal();
</script>
</body>
</html>

 效果图:

 

这是普通方法和插件方法的区别

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
</head>
<body>
<div class="fix"></div>
<script type="text/javascript" src="jquery-1.10.1.min.js"></script>
<script>
(function($){
$.fn.tooltip1 = function(){
	console.info("111");
};
$.prototype.tooltip2 = function(){
	console.info("222");
};
$.fn.extend({
	tooltip3:function(){
		console.info("333");
	}
});
$.prototype.extend({
	tooltip4:function(){
		console.info("444");
	}
});
$.extend({
	tooltip5: function(){
		console.info("555");
	}
});
})(jQuery);
$(function(){
	//这是插件的方法
	//使用参数进行调用
	$(".fix").tooltip1();
	$(".fix").tooltip2();
	$(".fix").tooltip3();
	$(".fix").tooltip4();
	//直接$调用
	$.tooltip5();
	
	//这是普通的方法
	fun1();
	fun2();
});
var fun1 = function(){
	console.info("fun1");
};
function fun2(){
	console.info("fun2");
};
</script>
</body>
</html>

 效果图:

 

猜你喜欢

转载自onestopweb.iteye.com/blog/2333361