zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    《javascript高级程序设计》第六章总结
    电子邮件写信页面开发代码
    JSON和XML的比较
    2014前端工程师基础课程作业
    cookie 和session 的区别详解
    substring()、slice()和substr()方法辨析
    Number()、parseInt()和parseFloat()辨析
    《javascript高级程序设计》第十三章知识点
    angular debounce 搜索去抖动/防抖
    js四舍五入保留两位小数的方法
  • 原文地址:https://www.cnblogs.com/shamgod/p/5499855.html
Copyright © 2011-2022 走看看