jQuery扩展

  • $仅仅是jQuery对象的一个别名。
  • 每次调用jQuery(),都会产生一个全新的jQuery对象,该对象继承了所有的内置的方法,这些方法都定义在$.fn对象中。
  • $.extends(target.obj1,obj2,...),它把多个object对象的属性和方法合并到一个target对象中,遇到同名属性时,总是使用靠后的对象的值,越后优先级越高。

index.html

<!DOCTYPE html>
<html>
<head>
	<title>Test JQuery extends</title>
	<!--微软CDN-->
	<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.min.js"></script>
	<!--MyExtends.js与index.html在同一目录下-->
	<script type="text/javascript" src="MyExtend.js"></script>
</head>
<body>
	<h1 id="test1">Test1 Jquery Extends</h1>
	<h1 id="test2">Test2 jQuery Extends</h1>
	<h1 id="test3">Test3 jQuery Extends</h1>
	<h1 id="test4">Test4 jQuery Extends</h1>
	<h1 id="test5">Test5 jQuery Extends</h1>
</body>
</html>

MyExtend.js

//开启精确模式
'use strict';
$(document).ready(function(){
	//添加扩展方法1
 	$.fn.modifyColor=function(options){
 	    //合并默认值与用户的设定值
 		var opts=$.extend({},$.fn.modifyColor.defaults,options);
 		this.css('backgroundColor',opts.bgColor).css('color',opts.color);
 		//保证链式编程
 		return this;
 	};
 	//要在添加了扩展方法之后,预设默认值
    $.fn.modifyColor.defaults={
        color:'white',
        bgColor:'black'
    };
 	//Test1-预设的默认值
	$('#test1').modifyColor();
	//Test2-改变默认值
 	$.fn.modifyColor.defaults={
		color:'yellow',
		bgColor:'blue'
	};
 	$('#test2').modifyColor();
 	//Test3-传参数代替默认值
	$('#test3').modifyColor({
        color:'red',
        bgColor:'green'
	});
	//添加扩展方法2
	jQuery.fn.extend({
	  modifyBackGround1: function() {
	  	this.css('backgroundColor','red');
	    return this;
	  },
	  modifyBackGround2: function() {
	  	this.css('backgroundColor','green');
	    return this;
	  }
	});
	//Test4
	$('#test4').modifyBackGround1();
	//Test5
	$('#test5').modifyBackGround2();
});
posted @ 2017-10-18 21:47  jiehuifang  阅读(96)  评论(0编辑  收藏  举报