How to run jQuery method from String

Say we have the following jQuery plugins

$.accordion(); $.button(); 

and in the script we have the following code:

 var plg = "accordion"; $('selector').plg(); plg = 'button'; $('selector').plg(); 

The above example, ofcource does not work. But is there a way to do something like this without using eval ()?

Can I run jQuery plugins from a variable?

+4
source share
2 answers

Of course you can!

 var plg = "accordion"; $('selector')[plg](); 
+5
source

If you want to create an alias for this function, you can simply assign it, there is no need for a string or eval :

 var plg = $.accordion; $('selector').plg(); 
+2
source

Source: https://habr.com/ru/post/1443802/


All Articles