【问题标题】:Can I call jQuery method with given selector, method name and variable arguments?我可以使用给定的选择器、方法名称和变量参数调用 jQuery 方法吗?
【发布时间】:2013-05-30 23:21:28
【问题描述】:

我试图通过网络搜索找到路,但我找不到。

我想做的是像下面这样调度 jQuery 方法;

var dispatchFunction = function (selector, jQueryMethod, jQueryArgs) {
    jQuery(selector)[jQueryMethod].apply(this, jQueryArgs);
}

虽然看起来像

jQuery("#id")["methodName"]

是一个函数。但是当我在 javascript 控制台中对该函数调用“应用”时,它不会像下面那样工作;

func = jQuery("#todo")["text"];
=> function (e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)}

jQuery("#todo")["text"]();
=> "abc"

func.apply(this);
=> ""

func.apply(this, []);
=> ""

有什么办法吗?

【问题讨论】:

  • 不知道我明白了,你不能这样做 -> $(variable1)[variable2](variable3); ??
  • 为什么要将函数放在变量中?为什么要匿名?为什么不给函数命名,然后像往常一样调用它?
  • @Phillip 因为我的代码需要接收一些方法调用,并尽可能处理它们,或者将它们委托给 jQuery。所以我需要将方法动态地分派给 jQuery。
  • @adeneo 我需要使用可变参数调用 jQuery 方法。所以可以有多个参数,如变量 3、变量 4 等。这就是我尝试使用“应用”的原因。
  • Phillip 可能在谈论使用 var 的函数声明 - 你可以写成 function dispatchFunction(...)。但这与您的问题有关。

标签: jquery call apply dispatch


【解决方案1】:

你需要做的是:

var dispatchFunction = function (selector, jQueryMethod, jQueryArgs) {
    var selection = jQuery(selector);
    selection[jQueryMethod].apply(selection, jQueryArgs);
}

您可能想阅读更多关于 this 关键字和 JS 中的函数与方法调用的信息。

【讨论】:

  • 非常感谢!你的回答解决了我的问题。我真的很感激你。 :)
猜你喜欢
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 2017-11-01
  • 2020-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-18
相关资源
最近更新 更多