[英]How to execute a JavaScript function when its name is passed as a string in function?
how can I use function name passed as argument. 如何使用作为参数传递的函数名称。
example: 例:
showError('container', 'id', '- message', 'show');
showError('container', 'id', '', 'hide');
function showError(container, id, msg, action)
{
if(action == 'show') {
$('#' + container).show();
$('#' + id).html(msg).show();
}
else {
$('#' + container).hide();
$('#' + id).html(msg).hide();
}
}
obj.foo()
really is a 2 step thing. obj.foo()
实际上是两步操作。 obj.foo
returns a function object, and then the ()
executes it. obj.foo
返回一个函数对象,然后()
执行它。 obj['foo']
returns the same function object, so add a ()
to execute it. obj['foo']
返回相同的函数对象,因此添加()
以执行它。
Since obj['foo']
is the same as obj.foo
. 由于
obj['foo']
与obj.foo
相同。 Even if the value on that property is a function. 即使该属性上的值是一个函数。 So you can always access any property with the
[]
accessor, using a string as the key name. 因此,您始终可以使用
[]
访问器,并使用字符串作为键名来访问任何属性。
$('#' + container)[action]();
Use bracket notation to access the respective method by a string: 使用括号表示法通过字符串访问相应的方法:
function showError(container, id, msg, action) {
$('#' + container)[action]();
$('#' + id).html(msg)[action]();
}
However, your method looks strange. 但是,您的方法看起来很奇怪。 I'd recommend to limit the action to the two values, and do that automatically:
我建议将操作限制为两个值,然后自动执行操作:
function showError(container, id, msg) {
var action = msg=='' ? 'hide' : 'show';
$('#' + container)[action]();
$('#' + id).text(msg)[action]();
}
In the general case, the bracket notation is good. 在一般情况下,括号表示法是好的。 In your case, use
toggle
: 在您的情况下,请使用
toggle
:
function showError(container, id, msg, action)
{
$('#' + container).toggle(action === 'show');
$('#' + id).html(msg).toggle(action === 'show');
}
or even (as Bergi suggests): 甚至(如Bergi建议的那样):
function showError(container, id, msg)
{
$('#' + container).toggle(!!msg);
$('#' + id).html(msg);
}
(It uses my own invention, the double-bang !!
, which converts truthy or falsy values to their Boolean equivalents.) (它使用了我自己的发明,double-bang
!!
,它将真值或伪值转换为布尔值。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.