jquery中的$.fn的用法

 ̄綄美尐妖づ 提交于 2020-04-25 16:56:31

一、$.fn.method()=function(){}和$.fn.extend({})的比较

jQuery.fn === jQuery.prototype

1.$.fn.method()=function(){}的调用把方法扩展到了对象的prototype上,所以实例化一个jQuery对象的时候,它就具有了这些方法。

比如:

$.fn.myExtension = function(){
 var currentjQueryObject = this;
 //work with currentObject
 return this;//you can include this if you would like to support chaining
};
$.fn.blueBorder = function(){
 this.each(function(){
  $(this).css("border","solid blue 2px");
 });
 return this;
};
$.fn.blueText = function(){
 this.each(function(){
  $(this).css("color","blue");
 });
 return this;
};

由于有return this,所以支持链式,在调用的时候可以这样写:$('.blue').blueBorder().blueText();

2.$.fn.extend({}) 是对$.fn.method()=function(){}的扩展,它可以定义多个方法:

$.fn.extend({
    a: function() { },
    b: function() { }
});

等效于:

$.fn.a = function() { };
$.fn.b = function() { };

二、$.extend({})  ,为jQuery类添加方法,可以理解为扩展静态方法

 

$.extend({
    abc: function(){
        alert('abc');
    }
});

 

usage: $.abc(). (No selector required like $.ajax().)

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!