当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jQuery $.extend()用法总结

jQuery $.extend()用法总结

2019年03月25日  | 移动技术网IT编程  | 我要评论

jquery为开发插件提拱了两个方法,分别是:
jquery.fn.extend(object);

jquery.extend(object);
jquery.extend(object);为扩展jquery类本身.为类添加新的方法。
jquery.fn.extend(object);给jquery对象添加方法。这个应该很好理解吧。举个例子。

. 代码如下:


<span style="font-size:18px;"><html>
<head>
<title></title>
</head>
<body>
<h3 class="ye">new soul</h3>
<h3 class="ye">new soul</h3>
<h3 class="ye">new soul</h3>
<h3 class="ye">new soul</h3>
<script type="text/javascript" src="jquery.2.0.3.js"></script>
<script type="text/javascript">
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 easy,yes?",css:{"color":"green","font-size":"20px"}});
</script>
</body>
</html>
</span>


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

1.合并多个对象。

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

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

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

. 代码如下:


<span style="font-size:18px;">//用法: jquery.extend(obj1,obj2,obj3,..)
var css1={size: "10px",style: "oblique"}
var css2={size: "12px",style: "oblique",weight: "bolder"}
$.jquery.extend(css1,css2)
//结果:css1的size属性被覆盖,而且继承了css2的weight属性
// css1 = {size: "12px",style: "oblique",weight: "bolder"}
</span>


2.深度嵌套对象。

. 代码如下:


<span style="font-size:18px;"> jquery.extend(
{ name: “john”, location: { city: “boston” } },
{ last: “resig”, location: { state: “ma” } }
);
// 结果:
// => { name: “john”, last: “resig”, location: { state: “ma” } }
// 新的更深入的 .extend()
jquery.extend( true,
{ name: “john”, location: { city: “boston” } },
{ last: “resig”, location: { state: “ma” } }
);
// 结果
// => { name: “john”, last: “resig”,
// location: { city: “boston”, state: “ma” } }
</span>


3.可以给jquery添加静态方法。

. 代码如下:


<span style="font-size:18px;"><html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="jquery.2.0.3.js"></script>
<script type="text/javascript">
$.extend({
add:function(a,b){return a+b;},
minus:function(a,b){return a-b},
multiply:function(a,b){return a*b;},
pide:function(a,b){return math.floor(a/b);}
});

var sum = $.add(3,5)+$.minus(3,5)+$.multiply(3,5)+$.pide(5,7);
console.log(sum);
</script>
</body>
</html></span>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网