call variable jQuery function

2019-02-25 18:01发布

问题:

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