有没有一种方法可以访问上一个链中的jQuery对象

Is there a way to access jQuery object from previous chain?

本文关键字:上一个 访问 对象 jQuery 方法 一种 有没有      更新时间:2023-11-22

不知道如何搜索这些类型的问题/答案。。。

这就是我要做的…

(function($){
    $.fn.helloworld = {
        want: function () {
            alert("I want" + this + "!");
        }
    };
})(jQuery);

现在,当我以这种方式调用函数,并尝试检索this时,它只会给我helloworld"对象"。

$("#test").helloworld.want();

有没有办法从内部访问调用方元素#test

没有"好"的方法。你可以这样做:

var $test = $('#test');
$test.helloworld.want.call($test);

问题是,通过建立你所拥有的结构,你本质上是在强迫你说你不想要的行为。

你可以做的是:

$.fn.helloworld = function( action ) {
  var actions = {
    test: function() {
      alert("Hi!");
    },
    // ...
  };
  if (actions[action])
    return actions[action].apply(this, [].slice.call(arguments, 1));
  return this;
};

现在你可以称之为:

$('#this').helloworld("test");