有没有办法从以前的链访问jQuery对象?

时间:2013-11-28 14:26:38

标签: javascript jquery

不确定如何搜索这类问题/答案......

这就是我想要做的......

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

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

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

有没有办法从内部访问来电元素#test

1 个答案:

答案 0 :(得分:4)

没有“好”的方式。你可以这样做:

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");