views:

39

answers:

2

Hello,

Is it possible to call a function by using the strings ?.

i.e i have a variable var target = 'next';. Using this string i want to call the jquery method next() . Should i use target + '()' (this is bit foolish) to call next() ???

I know it can be done using conditional statements. Since it is a var got from users, it is a heavy work to use conditional statements for all that.

i.e users will enter prev, siblings etc. So the respective functions should be called.

In my current project, i use more conditional statements for this thing. So i am fainted and it is difficult to manage.

I know it is bit impossible but any alternative suggestions will be helpful.

+6  A: 

You can use the bracket notation to access the member with a string containing the identifier:

var target = 'next';
$("foobar")[target]();    // identical to $("foobar").next()
Gumbo
wow don't know this one ! this really reduced my lines of code !
Aakash Chakravarthy
+2  A: 

If you're wanting to use jQuery, the answer is quite elegant. Because jQuery is an object (which can be accessed like an array) - you can use $("selector")target.

Examples:

var target = 'next';
jQuery("selector")[target]();

This will work if you know that you can trust the input. However, if you're not sure of this, you should check that the function exists before trying to run it otherwise you'll get an error.

var target = 'doesNotExist';
jQuery.fn[target] && jQuery('selector')[target](); // won't get to the right hand side of the && - so no errors
slightlymore