call variable jQuery function

穿精又带淫゛_ 提交于 2019-12-01 21:50:03

jQuery functions are still just JavaScript functions, so the same rules apply to them as any other JS functions.

You can call methods of an object objectVar as follows:

objVar.method();
objVar["method"]();
var methodName = "method";
objVar[methodName]();

Your question mentioned using window[]() - that applies to global functions, since they are essentially properties of window (if running JS in the browser, of course).

In the case of jQuery, you can therefore do this:

var methodName = "hide";
$(someSelector)[methodName]();
$(someSelector)[anyJSExpressionThatReturnsAStringThatIsAjQueryMethod]();

EDIT: I just saw the new version of the question. The line of code shown with the ?: operator selecting the method name should give the same effect as the if/else. I've used similar code myself with no problems, and it works fine in the fiddle that Jason P provided. Note that since your motivation here seems to be about making the code shorter you can omit all of the parentheses from the expression in the [] and just do this:

$("#gridViewContainer")[msg.length > 0?'slideDown':'slideUp']();

...or even omit the > 0 part since msg.length will be truthy when non-zero:

$("#gridViewContainer")[msg.length ?'slideDown':'slideUp']();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!