0

I try to replace a jquery chaned function with a var but it doesnt work (synthax error)

Triing something like this:

var foo = 'next()';
$(this).+foo+.show();

Is it possible somehow to realize that? foo is a var which changes to 'prev()' in another if condition

2
  • 2
    Only with eval; don't. Instead, use conditionals. Commented Feb 2, 2012 at 17:28
  • 2
    No, not only with eval. Also, if you're going to mention conditionals, you should offer ggzone a bit of advice on where to learn about them :) Commented Feb 2, 2012 at 17:32

3 Answers 3

3

Do it like this:

var foo = 'next';
$(this)[foo]().show();

By setting only the method name to the variable, you can use the [] notation and use the variable to retrieve the next property of the jQuery object.

This is equivalent to...

$(this)['next']().show();

which is equivalent to...

$(this).next().show();
Sign up to request clarification or add additional context in comments.

4 Comments

that way you are not invoking foo
Just to build on this, in JavaScript foo.bar and foo['bar'] mean the same thing, with foo['bar'] having that advantage that you can use a variable for the key.
You'll need [foo]() to execute the method.
@zapthedingbat: Thanks, yeah I forgot the () at first but added them back in when updating.
3

try this:

var foo = 'next';
$(this)[foo]().show();

Comments

-1

You have two options that I see:

var foo = next; // use the OBJECT here, not a string
$(this).foo().show();

OR

var foo = false;
if (foo)
  $(this).next().show()
else
  $(this).prev().show();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.