jQuery - 链接自定义函数

jQuery - Chaining custom functions

我想知道如何链接我的自定义函数并维护 '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 属性 'bar' of undefined

您需要 return 当前元素上下文,即来自您自定义方法的 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();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Return 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();

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/