概念:$.extend()与$.fn.extend的区别
$.extend就是只能用于$来调用的,例如$.extend({getName:function(){return this.name}}),调用$.getName()
而$.fn.extend()就是在$.fu上面扩展方法,可以用于所有对象,为什么?源码:$.fn=$.prototype,就是原型啊,可以被任何对象继承的,而$就只有这个类可以使用。
开发插件:
1、在全局加入这个方法
$.fn.greenify = function() {
this.css( "color", "red" );
return this;
};
$( "a" ).greenify(); // Makes all the links red.
2、链式操作,上面this代表$.fn,每操作完都会返回调用函数的对象
3、当然,使用JQUERY选择器的都是一些元素集合,如果要让调用函数对这些元素逐个执行,就要使用$.each().
$.fn.myNewPlugin = function() {
return this.each(function() {
// Do something to each element here.
});
};
4、如果需要设置
(function ( $ ) {
$.fn.greenify = function( options ) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
color: "#556b2f",
backgroundColor: "white"
}, options );
// Greenify the collection based on the settings variable.
return this.css({
color: settings.color,
backgroundColor: settings.backgroundColor
});
};
}( jQuery ));
5、命名空间
(function($){
})(JQuery)
这样是释放$这个符号,就可以用$来引用除Jquery库以外的库了。