原文: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();
    });

 

posted on 2015-07-25 20:40  grape1211  阅读(589)  评论(0编辑  收藏  举报