jQuery中$.fn的用法

原文:http://www.jb51.net/article/42816.htm

$.fn是指jquery的命名空间,$.fn=$.prototype。

1.$.extend

为jquery添加静态方法,与$.support,$.each类似

$.extend({ 
  add:function(a,b){returna+b;} 
});
$.add(1,2);


 1 function test(){
 2         function nPlugin(){
 3             alert('1');
 4             alert(this.add(1,4));
 5         }
 6 
 7         //与nPlugin.prototype.add=function(a,b){} 同
 8         $.extend(nPlugin.prototype,{ 
 9           add:function(a,b){return a+b;} ,
10             plus:function(a,b){return a*b}
11         }); 
12     }
13 
14     $(function () {
15         alert(11111);
16         test();
17         $.nPlugin();//失效
18         nPlugin(); //失效
19 
20         var a=new nPlugin();//有效
21     a.add(1,2);
22 });

 

2.$.fn.extend(object)

函数

 1 $.fn.extend({ 
 2 
 3 alertWhileClick:function(){ 
 4      alert('1111111111')
 5 }); 
 6 } 
 7 }); 
 8 
 9 
10 $('#div').alertWhileClick();

 

对象

function test(){
          var defaults = {
            width: 200,
            height: 0,
            event: 'click touchstart' // click, touchstart
          };

        function nPlugin(element,options){
            this.element = element;
            this.settings = $.extend({}, defaults, options);
            //alert($(element).html())
            alert('1');
            alert(this.add(1,4));
            obj =this;

            $(this.element).bind('click',function(){
                obj.show();
            });
        }

        //与nPlugin.prototype.add=function(a,b){} 同
        $.extend(nPlugin.prototype,{ 
          add:function(a,b){return a+b;} ,
            plus:function(a,b){return a*b},
            show:function(){
                alert($(this.element).html())
            }
        }); 

        //与$.fn.extend({nPlugin:funtion(){  }}) 同
        //与$.fn.nPlugin=function(){} 同
        $.fn['nPlugin'] = function(options) {
             this.each(function() {
                 if (!$.data(this, "plugin_"+ "nPlugin")) {
                 $.data(this, "plugin_" + "nPlugin", new nPlugin(this, options));
                 //new Plugin(this, options);
             }
             });
            
            return this;
        };

    }

    $(function () {
        test();
        alert('333333333333')
         $('#text').nPlugin();
         $('#text').nPlugin().data('plugin_nPlugin').show();
    });

 

转载于:https://www.cnblogs.com/grape1211/p/4676536.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值