jquery编写自己的插件

来源:互联网 发布:c语言二级文件系统 编辑:程序博客网 时间:2024/05/17 22:09

封装对象方法的插件

通过选择器获取到jquery对象,调用插件函数。
插件函数挂在$.fn上,$.fn是jQuery构造函数的原型对象。

;$(function($){    $.fn.Bar=function(value){    }})(jQuery);;$(function($){    $.fn.extend({        "bar":function(value){        }    });})(jQuery);

例子:设置和获取字体颜色的插件

;(function($){    $.fn.extend({        color:function(value){            if(value)                return this.css('color',value);            else                return this.css('color');        }    });})(jQuery);$('p').color('red');console.log($('p').color());//rgb(255, 0, 0)

封装全局函数的插件

插件函数挂在JQuery对象上。通过JQuery调用插件函数。

;$(function($){    $.Bar=function(){    }})(jQuery);;$(function($){    $.extend({        "bar":function(value){        }    })})(jQuery);

例子–删除字符串左边的空格

;(function($){    $.extend({        ltrim:function(value){            return (value||"").replace(/^\s+/g,"");        }    })})(jQuery);var str="   abc   ";console.log($.ltrim(str));//abcconsole.log(str);//   abc

选择器插件–自定义选择器(少用)

$("div:between(2,5)")//获取第3、4个div元素,从0算起//对所有的div执行between函数,如果返回true则选中,如果返回false则不选中$.extend($.expr[":"],{    between:function(a,i,m){        return true;    }})

例子–选中第3、4个元素

;(function($){    $.extend($.expr[":"],{        between:function(a,i,m){            var tmp=m[3].split(",");            return tmp[0]-0<i&&tmp[1]-0>i;        }    })})(jQuery);$('p:between(2,5)').css('color','red');

经过测试,使用1.7.1版本的jquery,以上代码正确执行。使用新版本jquery,不能正确执行,i不是代表当前元素的索引,而是0。

$.extend()

除了可以用于扩展jQuery对象之外,还能用于扩展已有Object对象。

$.extend(obj1,obj2);//用obj2的属性来替换obj1中相同的属性

例子

;(function($){    $.fn.extend({        color:function(value){            var value=$.extend({                color:'red'            },value);            return this.css('color',value.color);        }    });})(jQuery);$('p').color({color:'green'});$('a').color();//使用默认颜色红色
1 0
原创粉丝点击