分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

jQuery $.extend()用法总结

发布时间:2023-09-06 01:56责任编辑:胡小海关键词:jQuery

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);   

jQuery $.extend()用法总结

原文地址:https://www.cnblogs.com/yy1234/p/9099833.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved