简单来讲,jQuery.fn.extend() 是为jQuery对象添加自定义方法。使用方法:jQuery(".test").XXX();//XXX为自定义方法
jQuery.fn.extend()是为jQuery添加方法,相当于jQuery的静态方法。使用方法:jQuery.XXX();//XXX为自定义方法
通常写插件的格式为
//开始前有分号,是为了更好的兼容性
;(function($){
/*$作为匿名函数的形参,是jQuery的缩写别名,也可以用其他符号代替,一般习惯用$符号*/
})(jQuery); //这里将jQuery作为实参传递给匿名函数
举个例子:
1、插件代码
;(function($){
$.fn.extend({
"color": function(value){
if(value == undefined){
return this.css("color");
}else{
return this.css("color", value);
}
}
});
$.extend({
add: function(a,b){
return a+b;
}
});
})(jQuery);
2、调用代码
$(function(){
$(".span").color("red");
alert($(".span1").color());//弹出颜色值
var a = $.add(1,2);
alert(a);//弹出结果3
})
3、页面代码
<span class="span">body</span>
<label class="span1" style="color: blue;">bodya</label>