replace jquery function with var
-
21-04-2021 - |
Question
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
Solution
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();
OTHER TIPS
try this:
var foo = 'next';
$(this)[foo]().show();
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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow