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

问题描述

这似乎很简单,但是我找不到 jQuery 函数来处理.

This seems like such a straight-forward thing to do, but I can't find a jQuery function to handle this.

例如

$('div').show().sayHi()

function sayHi(obj) {
    obj.html('hi')
}

sayHi()不是 jQuery 函数,因此无法在此上下文中调用.您需要这样称呼它:

sayHi() is not a jQuery function so it can't be called in this context.You would need to call it like:

var $div = $('div').show()
sayHi($div)

但是我希望它是链中的一部分,主要是因为它看起来更好.

But I want it as part of the chain, mostly because it looks nicer.

解决方案:

Barmar的答案最好地回答了这个特定问题,但是我的实现是一个更可重用的选择,如下面我的回答所示.

Answer from Barmar best answers this specific question, but my implementation was a more reusable option, as shown in my answer below.

推荐答案

您可以通过将其定义为$.fn的属性来添加自己的jQuery方法.所以你可以这样写:

You can add your own jQuery method, by defining it as a property of $.fn. So you can write:

$.fn.sayHi = function() {
  this.html('Hi');
  return this;
}

$("#click").click(function() {
  $("#foo").show().sayHi();
});
#foo {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click">Click me</button><br>
<div id="foo"></div>

按照惯例,不返回与对象有关的信息的jQuery方法应返回this,以便它们可以继续被链接.

By convention, jQuery methods that don't return information related to the object should return this so they can continue to be chained.

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

08-16 07:53