扩大
缩小

jQuery $.extend()用法总结

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

 

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


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

举个例子

[html] view plain copy
 
  1. <h3 class="ye">new soul</h3>   
  2. <h3 class="ye">new soul</h3>   
  3. <h3 class="ye">new soul</h3>   
  4. <h3 class="ye">new soul</h3>   
  5. <script type="text/javascript" src="jquery.2.0.3.js"></script>   
  6. <script type="text/javascript">   
  7. jQuery.fn.myPlugin = function(options) {   
  8. $options = $.extend( {   
  9. html: "no messages",   
  10. css: {   
  11. "color": "red",   
  12. "font-size":"14px"   
  13. }},   
  14. options);   
  15. return $(this).css({   
  16. "color": $options.css.color,   
  17.   
  18. }).html($options.html);   
  19. }   
  20. $('.ye').myPlugin({html:"So easy,yes?",css:{"color":"green","font-size":"20px"}});  

好的,上面你也看到了一点点$.extend()的用法。 

1.合并多个对象。 

这里使用的就是$.extend()的嵌套多个对象的功能。 

所谓嵌套多个对象,有点类似于数组的合并的操作。 

但是这里是对象。举例说明:

[javascript] view plain copy
 
  1. //用法: jQuery.extend(obj1,obj2,obj3,..)   
  2. var Css1={size: "10px",style: "oblique"}   
  3. var Css2={size: "12px",style: "oblique",weight: "bolder"}   
  4. $.jQuery.extend(Css1,Css2)   
  5. //结果:Css1的size属性被覆盖,而且继承了Css2的weight属性   
  6. // Css1 = {size: "12px",style: "oblique",weight: "bolder"}   

 

2.深度嵌套对象。

[javascript] view plain copy
 
  1.  jQuery.extend(   
  2. { name: “John”, location: { city: “Boston” } },   
  3. { last: “Resig”, location: { state: “MA” } }   
  4. );   
  5. // 结果:   
  6. // => { name: “John”, last: “Resig”, location: { state: “MA” } }   
[javascript] view plain copy
 
  1. // 新的更深入的 .extend()   
  2. jQuery.extend( true,   
  3. { name: “John”, location: { city: “Boston” } },   
  4. { last: “Resig”, location: { state: “MA” } }   
  5. );   
  6. // 结果   
  7. // => { name: “John”, last: “Resig”,   
  8. // location: { city: “Boston”, state: “MA” } }   


3.可以给jQuery添加静态方法

[javascript] view plain copy
 
    1. $.extend({   
    2. add:function(a,b){return a+b;},   
    3. minus:function(a,b){return a-b},   
    4. multiply:function(a,b){return a*b;},   
    5. divide:function(a,b){return Math.floor(a/b);}   
    6. });   
    7. var sum = $.add(3,5)+$.minus(3,5)+$.multiply(3,5)+$.divide(5,7);   
    8. console.log(sum);   

posted on 2018-05-28 14:04  禅道  阅读(202)  评论(0编辑  收藏  举报

导航