问题:想要把库方法和函数转换到一个jQuery插件中,以方便其他人调用
解决方案:
+ 如果你的插件有一个或多个单独的函数,并且它们不需要加入到jQuery链,在fn属性上创建一个函数:
$.fn.setColor = function(color){
this.css("color",color);
}
- 如果想要自己的方法能够加入到jQuery方法链中
$.fn.increaseWidth = function(
{
return this.each(function(){
var width = $(this).width()+10;
$(this).width(width);
});
};
- 如果你的函数使用 $ 符,并且你想要使该库能与使用了 $ 符的其他库一起使用,将你的函数包含到一个匿名函数中
;(function($){
$.fn.flashBlueRed = function(){
return this.each(function(){
var hex = rgb2hex($(this).css("background-color"));
if(hex =="#0000ff"){
$(this).css("background-color","#ff0000");
}else{
$(this).css("background-color","#0000ff");
}
});
};
})(jQuery);
注意:
+ return this.each(function(){..});要允许该方法在选择器所返回的任何内容上工作,不管它是一个单独的项还是一组项,此段代码必须有。
+ 匿名函数前加分号:确保了如果任何插件忘记使用一个分号来终止一个方法或者函数的话,该函数也不会失效。