eawer
eawer

Reputation: 1458

Calling a jQuery method named in variable

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)

I tried

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

but it gives this error:

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

Upvotes: 1

Views: 287

Answers (4)

DayTimeCoder
DayTimeCoder

Reputation: 4332

Try this:

function fun(funcName){
  return $('img')[funcName]('src');
}

fun('attr');

This is a pretty simple approach but it works ,because $('img').attr('src') is same if you wrote this $('img')['attr']('src')

Upvotes: 0

Alnitak
Alnitak

Reputation: 339816

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

See http://jsfiddle.net/7rBDe/1/

Upvotes: 9

istruble
istruble

Reputation: 13702

What you are describing as method is actually a combination of a method and a parameter. If you can break things up into just the method name and just the parameter you can do something like this:

var method = 'attr';
var param = 'class';
$('.post-text')[method](param);  // returns "post-text" on this page.

Which is the same thing as:

$('post-text').attr('class');

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74420

You could use new function too, not same scope than eval:

(new Function( "return $('img')."+method )())

http://jsfiddle.net/J9zU4/

Upvotes: 0

Related Questions