当前位置: 移动技术网 > IT编程>开发语言>Jquery > jquery中方法扩展 ($.fn & $.extend) 学习笔记

jquery中方法扩展 ($.fn & $.extend) 学习笔记

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

a、$.fn

1、$.fn.method() 函数为jquery对象扩展一个属性和方法(主要用于扩展方法) ;method 为自定义方法名 ($.fn 等效 $.prototype)

 1   $.fn.borderset = function () {
 2     this.each(function () {
 3       $(this).css("border", "solid pink 2px");
 4     });
 5     return this;
 6   };
 7   $.fn.textcolor = function ($color) {
 8     this.each(function () {
 9       $(this).css("color", $color);
10     });
11     return this;
12   };
13 
14   $.fn.textsize = function () {
15     this.each(function () {
16       $(this).css("font-size", '40px');
17     });
18     return this;
19   };

2、$.fn.extend() 函数为jquery对象扩展一个或多个实例属性和方法(主要用于扩展方法)

 1 $.fn.extend({
 2     borderset: function () {
 3       this.each(function () {
 4         $(this).css("border", "solid pink 2px");
 5       });
 6       return this;
 7     },
 8     textcolor: function ($color) {
 9       this.each(function () {
10         $(this).css("color", $color);
11       });
12       return this;
13     },
14     textsize: function () {
15       this.each(function () {
16         $(this).css("font-size", '40px');
17       });
18       return this;
19     }
20   });

 

调用:

1 $('.test').borderset();
2 $('.test').textcolor('green');
3 $('.test').textsize();
4 
5  $('.test').borderset().textcolor('green').textsize();//方法包含return this,支持链式调用

 


b、$.extend

1、$.extend() 函数用于将一个或多个对象的内容合并到目标对象。对象具有相同的属性,则后者覆盖前者的属性值

1 var obj_1 = {a: 0, b: 9};
2 var obj_2 = {a: 1, c: 2};
3 $.extend(obj_1, obj_1);/* obj_2 合并到 obj_1 中 */
4 console.log(obj_1);
5 console.log(obj_2);

2、$.extend({}) 为jquery类扩展方法

1   $.extend({
2     alerttext: function ($text) {
3       alert($text);
4     }
5   });
6 
7   $.alerttext('this is a test !!!');

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

相关文章:

验证码:
移动技术网