jq插件的编写中(jquery.extend、jquery.fn与jquery.fn.extend的使用区别)

来源:互联网 发布:机器人编程语言py 编辑:程序博客网 时间:2024/05/21 07:47

1.jquery.extend的用法是对jquery对象进行方法的扩展,实则为jquery的一个属性。相当于为jQuery类添加类方法,可以理解为添加静态方法。如:

jQuery.extend({    min: function(a, b) { return a < b ? a : b; },    max: function(a, b) { return a > b ? a : b; }});//调用方法jQuery.min(3,4); //  3 jQuery.max(7,8); //  8//例如:$.ajax  应该就是使用这种方法。

2.jquery.fn相当与jquery.prototype(jquery的原型),写法如下:

(function($){    $.fn.插件名= function(){         // 插件代码写在这里      }     return this;  //便于链式调用})(jQuery);//调用方法$('选择器').pluginName() 

3.jquery. fn.extend相当于 jquery.prototype.extend的用法,就是对jquery的原型的扩展。

(function($){    $.fn.extend({                  event1:function() {                          $(this).click(function(){                                      alert($(this).val());                          })                   },         event2:function(){            //方法的代码写在这        }           })    return this;  //便于链式调用})(jQuery);//调用方法,原理现将jquery实例化,然后再调用原型上的方法。$("#input1").event1();$("#input1").event2();   

总结:jquery.fn 与 jquery.fn.extend 的作用基本一致,差别在于,前者只能跟一个插件;后者可以写多个方法 。

1 0
原创粉丝点击