【问题标题】:jQuery - Chaining custom functionsjQuery - 链接自定义函数
【发布时间】:2016-06-23 13:10:32
【问题描述】:

我想知道如何链接我的自定义函数并维护“this”的上下文。

例子:

$.fn.foo = function() {
  var html = '<div class="foo"></div>';
  if ($(this).hasClass(somthing) {
    $(this).prepend(html);
  }
}

$.fn.bar = function() {
  var html = '<h3>bar</h3>';
  $(this).find('.foo').prepend(html);
}

$('body').foo().bar();

当我尝试使用此代码时,我得到一个 TypeError: Cannot read property 'bar' of undefined

【问题讨论】:

    标签: javascript jquery method-chaining


    【解决方案1】:

    您需要从您的自定义方法返回当前元素上下文,即this

    $.fn.foo = function() {
      var html = '<div class="foo"></div>';
      if ($(this).hasClass('somthing')) {
        $(this).prepend(html);
      }
      return this; //The magic statement
    }
    
    $.fn.bar = function() {
      var html = '<h3>bar</h3>';
      $(this).find('.foo').prepend(html);
      return this; //The magic statement
    }
    
    $('body').addClass('somthing').foo().bar();
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

    【讨论】:

      【解决方案2】:

      返回this:

      $.fn.foo = function() {
          var html = '<div class="foo"></div>';
          if ($(this).hasClass(somthing) {
              $(this).prepend(html);
          }
          return this;
      };
      
      $.fn.bar = function() {
          var html = '<h3>bar</h3>';
          $(this).find('.foo').prepend(html);
          return this;
      };
      
      $('body').foo().bar();
      

      【讨论】:

        【解决方案3】:

        jQuery extend 函数可能正是您想要的。它允许您创建一个逗号分隔的函数列表,您可以在链式表达式中使用这些函数

        jQuery.fn.extend({
          check: function() {return this.each(function() { this.checked = true; });} ,  
          uncheck: function() {return this.each(function() { this.checked = false;  });
          }})
        

        用法:检查所有复选框:

        $( "input[type='checkbox']" ).check();
        

        (摘自https://api.jquery.com/jquery.fn.extend/的例子)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-08
          • 2011-04-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-03
          • 2014-10-13
          • 2018-03-21
          相关资源
          最近更新 更多