经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » jQuery » 查看文章
jquery中方法扩展 ($.fn & $.extend) 学习笔记
来源:cnblogs  作者:你看我哪里像好人  时间:2019/4/18 9:32:21  对本文有异议

A、$.fn

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

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

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

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

 

调用:

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

 


B、$.extend

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

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

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

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

原文链接:http://www.cnblogs.com/cmnull/p/10727547.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号