调用变量中命名的jQuery方法 [英] Calling a jQuery method named in variable

查看:94
本文介绍了调用变量中命名的jQuery方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript变量,其中包含jQuery方法的名称:

I have a JavaScript variable which contains the name of a jQuery method:

var method = 'attr("src")';

如何让它像以下一样工作:

How can I make it work like:

console.log($('img').method)

我试过

console.log($('img')[method]())

但它会出现此错误:

Uncaught TypeError: Object [object Object] has no method 'attr("src")'


推荐答案

你遇到的问题是方法名称​​和的参数都用单个字符串编码。

The issue you have is that you have both the method name and its parameters encoded in a single string.

如果您有一个数组,首先包含方法名称,然后是参数,这很容易,按照以下简单的插件我只是敲了一起:

If instead you had an array containing first the method name and then the parameters, this would be easy, per the following trivial plugin I just knocked together:

(function($) {
    $.fn.invoke = function(args) {
        var method = args.shift();
        return $.fn[method].apply(this, args);
    }
})(jQuery);

var method = ['attr', 'src'];
var src = $('img').invoke(method);

参见 http://jsfiddle.net/7rBDe/1/

这篇关于调用变量中命名的jQuery方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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