jQuery基础教程-第8章-002Adding jQuery object methods

一、Object method context

1.We have seen that adding global functions requires extending the jQuery object with new methods. Adding instance methods is similar, but we instead extend the jQuery.fn object(The jQuery.fn object is an alias to jQuery.prototype,provided for conciseness.):

1 jQuery.fn.myMethod = function() {
2     alert('Nothing happens.');
3 };

We can then call this new method from our code after using any selector expression:

1 $('div').myMethod();

Our alert is displayed (once for each <div> in the document) when we invoke the method.

 

2.交换CSS的类样式

 1 // Unfinished code
 2 (function($) {
 3     $.fn.swapClass = function(class1, class2) {
 4         if (this.hasClass(class1)) {
 5             this.removeClass(class1).addClass(class2);
 6         } else if (this.hasClass(class2)) {
 7             this.removeClass(class2).addClass(class1);
 8         }
 9     };
10 })(jQuery);
11 $(document).ready(function() {
12     $('table').click(function() {
13         $('tr').swapClass('one', 'two');
14     });
15 });

 

二、Implicit iteration

 1 (function($) {
 2     $.fn.swapClass = function(class1, class2) {
 3         this.each(function() {
 4             var $element = $(this);
 5             if ($element.hasClass(class1)) {
 6                 $element.removeClass(class1).addClass(class2);
 7             } else if ($element.hasClass(class2)) {
 8                 $element.removeClass(class2).addClass(class1);
 9             }
10         });
11     };
12 })(jQuery);

The meaning of "this"
Caution: The keyword this refers to a jQuery object within the object method's body, but refers to a DOM element within the .each() invocation.

 

三、Enabling method chaining

 1 (function($) {
 2     $.fn.swapClass = function(class1, class2) {
 3         return this.each(function() {
 4             var $element = $(this);
 5             if ($element.hasClass(class1)) {
 6                 $element.removeClass(class1).addClass(class2);
 7             } else if ($element.hasClass(class2)) {
 8                 $element.removeClass(class2).addClass(class1);
 9             }
10         });
11     };
12 })(jQuery);

 

转载于:https://www.cnblogs.com/shamgod/p/5499855.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值