call variable jQuery function

南笙酒味 提交于 2019-12-20 02:48:06

问题


I've been shown how to call variable javascript functions by using window[]().

Is it possible to call variable jQuery functions? If so, how?

Usually, I only need a ternary to flip a visible switch, and it would be very convenient to smush many lines of code into 1. For example, inside an $.aja() success:

if(msg.length > 0){
    $("#gridViewContainer").slideDown()
}
else{
    $("#gridViewContainer").slideUp()
}

This is probably a bad example since a boolean can probably be passed to slide() or something, but I'd like to use the concept in the linked question above.

This did not work for me:

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

回答1:


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']();


来源:https://stackoverflow.com/questions/18879115/call-variable-jquery-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!