调用变量jQuery函数 [英] call variable jQuery function

查看:79
本文介绍了调用变量jQuery函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已显示如何使用window[]()调用变量javascript function.

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

是否可以调用变量jQuery function s?如果可以,怎么办?

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

通常,我只需要一个三进制来翻转可见的开关,将许多代码行拖入1中会非常方便.例如,在$.aja() success中:

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()
}

这可能是一个不好的例子,因为boolean可能可以传递给slide()之类的东西,但是我想在上面的链接问题中使用该概念.

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.

这对我不起作用:

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

推荐答案

jQuery函数仍然只是JavaScript函数,因此与其他任何JS函数一样,它们也适用相同的规则.

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

您可以按以下方式调用对象objectVar的方法:

You can call methods of an object objectVar as follows:

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

您使用window[]()提到的问题-适用于全局函数,因为它们本质上是window的属性(当然,如果在浏览器中运行JS).

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).

对于jQuery,您可以执行以下操作:

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

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

我刚刚看到了问题的新版本.用?:运算符选择方法名称显示的代码行应具有与if/else相同的效果.我自己也使用过类似的代码,没有问题,并且在 Jason P提供的小提琴中可以正常工作.请注意,由于此处的动机似乎是使代码更短,因此可以省略[]中表达式的所有括号,只需执行以下操作:

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

...甚至省略> 0部分,因为msg.length在非零时将是真实的:

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

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

这篇关于调用变量jQuery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆