js插件化

概念:$.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库以外的库了。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值