jQuery-链接自定义函数 [英] jQuery - Chaining custom functions

查看:72
本文介绍了jQuery-链接自定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am wondering how to chain my custom functions and maintain context of '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:无法读取未定义的属性"bar"

When i try to use this code i get a TypeError: Cannot read property 'bar' of undefined

推荐答案

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

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>

这篇关于jQuery-链接自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆