最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery - Chaining custom functions - Stack Overflow

programmeradmin0浏览0评论

I am wondering how to chain my custom functions and maintain context of '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

I am wondering how to chain my custom functions and maintain context of '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

Share Improve this question asked Jun 23, 2016 at 13:10 Frederick M. RogersFrederick M. Rogers 9216 gold badges14 silver badges39 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 14

You need to return current element context, i.e. this from you custom method.

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

The jQuery extend function may be what you are looking for. 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/ )

发布评论

评论列表(0)

  1. 暂无评论