编写jQuery插件

jQuery编写插件

1、插件机制

jQuery提供两种扩展方法:

jQuery.fn.extend()
封装对象的方法

jQuery.extend()
封装全局函数和选择器插件

后者可以扩展jQuery对象也可以扩展已有的jquery对象

2、编写插件

(1)封装jquery对象的方法

;(function($){ //这里写插件代码 $.fn.extend({ 'color':function(value){ //这里写jquery对象的color方法 if(value==undefined){ //获取颜色值 return this.css('color'); }else{ //设置颜色值 return this.css('color',value); } } }); })(jQuery)

     上述代码可以简化为:

;(function($){ //这里写插件代码 $.fn.$.extend({ 'color':function(value){ //这里写jquery对象的color方法 return this.css('color',value); } }); })(jQuery)

(2)封装全局函数 调用的时候直接$.color()即可

;(function($){ //这里写插件代码 $.extend({ 'color':function(value){ //这里写jquery对象的color方法 return this.css('color',value); } }); })(jQuery)

(3) 自定义选择器

;(function($){ //这里写插件代码 $.extend($.expr[':'],{ between: function(a,i,m){ var tmp = m[3].split(','); return tmp[0]-0<i&&i<tmp[1]-0; } }); })(jQuery)
posted @ 2015-05-29 10:58  小彬同学  阅读(104)  评论(0编辑  收藏  举报