$.fn.extend()与$.extend()的使用

jQuery为开发插件提拱了两个方法,分别是:

JavaScript代码

  • jQuery.fn.extend(object);   
  • jQuery.extend(object);   

jQuery.extend(object); 为扩展jQuery类本身.为类添加新的方法。

jQuery.fn.extend(object);给jQuery对象添加方法。

jQuery便是一个封装得非常好的类,比如我们用 语句 $("#btn1") 会生成一个 jQuery类的实例。

 

jQuery.extend(object); 为jQuery类添加添加类方法,可以理解为添加静态方法。如:

 

$.extend({

  add:function(a,b){return a+b;}

});

 $(document).ready(function(e) {
jQuery.extend( {
    myshow:function(a,b)
    {
     return a+b;
    }
  })
$(".a").click(function() {
    alert($.myshow(3, 4));
});
});

</script>
<body>
<div class="a" style="color:black; 20px; height:30px;">sdddddddd</div>
<div class="a" style="color:yellow; 20px; height:30px;">ddddddddd</div>
<div class="a" style="color:black; 20px; height:30px;">ddddddddddd</div>
</body>

便为 jQuery 添加一个为 add 的 “静态方法”,之后便可以在引入 jQuery 的地方,使用这个方法了,

$.add(3,4); //return 7

 

jQuery.fn.extend(object); 对jQuery.prototype进得扩展,就是为jQuery类添加“成员函数”。jQuery类的实例可以使用这个“成员函数”。

比如我们要开发一个插件,做一个特殊的编辑框,当它被点击时,便alert 当前编辑框里的内容。可以这么做:

 

javascript代码
$.fn.extend({        
        
   alertWhileClick:function(){        
       
       $(this).click(function(){        
       
            alert($(this).val());        
        });        
        
    }        
        
});        
        
$("#input1").alertWhileClick(); //页面上为:<input id="input1" type="text"/>    

 

$("#input1") 为一个jQuery实例,当它调用成员方法 alertWhileClick后,便实现了扩展,每次被点击时它会先弹出目前编辑里的内容。

<script src="jquery-1.8.0.js"></script>
<script>
$(document).ready(function(e) {
jQuery.fn.extend({
    color:function(val)
    {
          if(val == undefined){
              return $(this).css("color");
          } else {
              return $(this).css("color",val);
          }
    }
})
$(".a").click(function() {
    $(this).color("red");//对jquery对象进行颜色设置
    alert($(this).color());//获取jquery对象的颜色,并用对话框弹出
});
});

</script>
<body>
<div class="a" style="color:black; 20px; height:30px;">sdddddddd</div>
<div class="a" style="color:yellow; 20px; height:30px;">ddddddddd</div>
<div class="a" style="color:black; 20px; height:30px;">ddddddddddd</div>
</body>

原文地址:https://www.cnblogs.com/luhangnote/p/2681899.html