JQuery-jQuery插件机制

为了扩展jQuery库函数,jQuery提供了两种方式

jQuery.extend(object)

  • 扩展jQuery对象本身,主要是用来扩展jQuery全局函数 ,调用时直接$.函数名(参数)
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/jquery-1.8.3.js" ></script>
		
	</head>
	<body>
		<script>
			$.extend({
				max:function(a,b) {
					return (a > b) ? a: b;
				},
				min:function(a,b){
					return (a < b) ? a: b;
				}
			});
			console.log($.max(4,5));
			console.log($.min(4,5));
			</script>
	</body>
</html>

结果
结果

  • 使用$调用max方法返回两个数的最大值,输出的结果为5,调用min方法返回两个数最小值输出为4

jQuery.fn.extend(object)

  • 扩展 jQuery 元素集,主要用于扩展jQuery插件,调用时需要先创建jQuery对象,然后才能调用相应的函数
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/jquery-1.8.3.js" ></script>
		
	</head>
	<body>
		<input type="checkbox" checked="checked" />乒乓球
		<input type="checkbox" />足球
		<input type="checkbox" />篮球
		<input type="checkbox" />网球
		<input type="checkbox" />橄榄球
		<input type="checkbox" />高尔夫
		<script>
			jQuery.fn.extend({
				check:function() {
					this.attr("checked","checked");
				},
				uncheck:function() {
					this.removeAttr("checked");
				}
			})
			$("input[type='checkbox']").check();
		</script>
	</body>
</html>

结果
结果

  • 使用属性选择器,把所有的input标签中属性type="checkbox"的元素设置属性checked="checked”。

注意

  • 为了避免自己定义的函数或者变量与外部冲突,对JQuery函数的扩展一般写在自执行匿名函数中。

比如下面的形式:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/jquery-1.8.3.js" ></script>
		
	</head>
	<body>
		<script>
			(function($){
				$.max=function(a,b){
					return (a > b) ? a: b;
				},
				$.min=function(a,b){
					return (a < b) ? a: b;
				}
			})(jQuery)
			console.log($.max(4,5));
			console.log($.min(4,5));
			</script>
	</body>
</html>

对于扩展 jQuery 元素集方式也写在自执行匿名函数中

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/jquery-1.8.3.js" ></script>
		
	</head>
	<body>
		<input type="checkbox" checked="checked" />乒乓球
		<input type="checkbox" />足球
		<input type="checkbox" />篮球
		<input type="checkbox" />网球
		<input type="checkbox" />橄榄球
		<input type="checkbox" />高尔夫
		<script>
			(function($){
				jQuery.fn.check = function(){
					this.attr("checked","checked");
				},
				jQuery.fn.uncheck=function() {
					this.removeAttr("checked");
				}
			})(jQuery)
			$("input[type='checkbox']").check();
		</script>
	</body>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值