简体   繁体   English

jQuery - 链接自定义函数

[英]jQuery - Chaining custom functions

I am wondering how to chain my custom functions and maintain context of 'this'. 我想知道如何链接我的自定义函数并维护'this'的上下文。

Example: 例:

$.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();

When i try to use this code i get a TypeError: Cannot read property 'bar' of undefined 当我尝试使用此代码时,我得到一个TypeError:无法读取未定义的属性“bar”

You need to return current element context, ie this from you custom method. 你需要返回当前元素上下文,即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 : 归还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();

The jQuery extend function may be what you are looking for. jQuery 扩展函数可能正是您正在寻找的。 It allows you to create a comma-separated list of functions that you can use in chained expressions 它允许您创建以逗号分隔的函数列表,您可以在链式表达式中使用这些函数

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

Usage: this checks all checkboxes: 用法:检查所有复选框:

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

(example extracted from https://api.jquery.com/jquery.fn.extend/ ) (从https://api.jquery.com/jquery.fn.extend/中提取的示例)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM