纯牛奶645
纯牛奶645
  • 发布:2018-02-06 10:19
  • 更新:2018-02-06 10:19
  • 阅读:1783

jquery $.extend()用法总结

分类:Native.js

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

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

jQuery.fn.extend(object);给jQuery对象添加方法。
jQuery.extend(object);为扩展jQuery类本身.为类添加新的方法。
注意用法上的区别
jQuery.fn.myPlugin的用法为 $('.ye').myPlugin
jQuery.extend的用法为 $.add(3,5);

jQuery.fn.myPlugin = function(options) {  
                $options = $.extend({  
                    html: "no messages",  
                    css : {  
                        "color":"red",  
                        "font-size": "14px"  
                    }},  
                    options);  
                    return $(this).css({  
                          "color": $options.css.color  
                    }).html($options.html);  
            }  
            $('.ye').myPlugin({  
                html: "so esay,yes?",  
                css: {"color":"green","font-size":"20px"}  
            });

1.合并多个对象
这是使用的就是$.extend( )的嵌套多个对象的功能。
所谓嵌套多个对象,有点类似于数组的合并的操作。但是这里是对象。举例说明:
用法 jQuery.extend(obj1,obj2,obj3...)

var css1 = {size:"10px",style: "oblique"};  
var css2 = {size:"12px",style:"oplique",weight:"bolder"};  
jQuery.extend(css1,css2);  
//结果:css1的size属性被覆盖,而且继承了css2的weight属性  
//css1 = {size: "12px",style: “oblique” ,weight: "bolder"}

2.深度嵌套对象

jQuery.extend(  
{name: "John",location: {city: "Boston"}},  
{last: "Resig",location:{state: "MA"}}  
);  
//结果  
// => {name:"John",last: "Resig",location:{state:"MA"}}   
//单层合并,city值丢失,后边的location覆盖了前边的location  

//更深入的 .extend()  
jQuery.extend(true,  
{name: "John",location: {city: "Boston"}},  
 {last: "Resig",location:{state: "MA"}}  
);  
//结果  
// => {name:"John",last: "Resig",location:{city:"Boston",state:"MA"}}  
//city与state合并为新的对象

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

$.extend({  
        add: function (a,b){  
            return a + b;  
        },  
        minus: function(a,b){  
            return a - b;  
        },  
        multiply: function(a,b){  
            return a*b;  
        },  
        divide:function(a,b){  
            return Math.floor(a/b);  
        }  
});  
var sum = $.add(3,5) + $.minus(3,5) + $.multiply(3,5)+ $.divide($options,7);  
console.log(sum);
0 关注 分享

要回复文章请先登录注册