jQuery插件高级编程

  1. 通过$.extend()来扩展jQuery

  2. 通过$.fn向jQuery中添加新方法

  3. 通过$.widget应用jQuery UI部件工厂方式创建

通过$.extend()方式添加:

仅仅是在jQuery命名空间或者理解成jQuery身上添加了一个静态方法而已,所以调用添加的jQuery方法时,
直接通过$符号调用如:$.function(),而不需要选中dom元素$('#example').myfunction()

$.extend({
    seyHello: function(name){
     console.log('Hello '+(name?name:'Dude')+'!');
    }
})
$.seyHello();
$.seyHello('跃跃');

$.extend()方法定义一些辅助方法是比较方便的,比如定义一个console,输出特定格式的信息,定义一次后,
可以通过jQuery在程序中任何需要的地方调用它,

$.extend({
    log : function(message){
     var now = new Date(),
      y = now.getFullYear(),//js的月份从0开始
      m = now.getMonth()+1,
      d = now.getDay(),
      h = now.getHours(),
      min = now.getMinutes(),
      s = now.getSeconds(),
      time = y + '-' + m + '-' + d + ' ' + h + ':' + min + ':' + s;
     console.log(time + ',' + message);
    }
});
$.log('好晚了啊!');

通过$.fn上面添加一个方法

其中名称是插件的名称,然后插件的代码在这个方法里面展开,比如调用插件时,被调用的元素字体颜色改为红色。这里this代表jQuery选择器返回的集合,通过jQuery的each方法遍历处理集合的单个元素,在each方法内部,this指带的是普通的dom元素,如果调用jQuery的方法就需要用$重新包裹下,比如

<ul>
	<li>
		<a href="http://www.webo.com/liuwayong">我的微博</a>
	</li>
	<li>
		<a href="http://http://www.cnblogs.com/Wayou/">我的博客</a>
	</li>
	<li>
		<a href="http://wayouliu.duapp.com/">我的小站</a>
	</li>
</ul>
<script type="text/javascript">
	$.fn.myPlugin=function(options){
		var defaults = {
			'color' : 'red',
			'fontSize' : '12px'
		};
		//注意这里的extends方法,它会将多个对象进行合并如:
		//var result=$.extend({},{name:"Tom",age:21},{name:"Jerry",sex:"Boy"})
		//执行extend方法后
		//result={name:"Jerry",age:21,sex:"Boy"}
		var setting = $.extend(defaults, options);
		return this.css({
			'color' : setting.color,
			'fontSize' : setting.fontSize
		})

	}
	$(function() {
		$('a').myPlugin({
			'color' : '#000',
			'fontSize' : '50px'
		});
	})
</script>

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注