[英]how to execute javascript function when i send its name as string dynamically with out parameters
I want execute javascript function which the name is coming as a string dynamically. 我想执行名称动态作为字符串来的javascript函数。 ansd i dont need to pass any parameters while executing the function.
Ansd我在执行功能时不需要传递任何参数。
Please can any one guide me how to achieve this? 请任何人指导我如何实现这一目标?
Regards, Kamesh 问候,卡梅什
one simple way 一种简单的方法
eval("SomeFunction()");
or 要么
var funcName = "SomeFunction";
var func == window[funcName];
func();
危险,但您可以使用eval(method_name+"()")
are you talking about ´eval()´?? 您在说“ eval()”吗?
var foo = "alert('bar')";
eval(foo);
Hope this helps; 希望这可以帮助;
function a() { console.log('yeah!'); } var funcName = 'a'; // get function name this[funcName]();
如果该函数是全局函数,则应在浏览器中执行window[funcName]()
。
Using eval
is the worst way imaginable. 使用
eval
是可想象的最糟糕的方法。 Avoid that at all costs. 不惜一切代价避免这种情况。
You can use window[functionname]()
like this: 您可以像这样使用
window[functionname]()
:
function myfunction() {
alert('test');
}
var functionname = 'myfunction';
window[functionname]();
This way you can optionally add arguments as well 这样,您还可以选择添加参数
Perhaps a safer way is to do something like this (pseudo code only here): 也许更安全的方法是执行以下操作(仅在此处使用伪代码):
function executer(functionName)
{
if (functionName === "blammo")
{
blammo();
}
else if (functionName === "kapow")
{
kapow();
}
else // unrecognized function name
{
// do something.
}
You might use a switch statement for this (it seems like a better construct): 您可以为此使用switch语句(似乎是一种更好的构造):
switch (functionName)
{
case "blammo":
blammo();
break;
case "kapow":
kapow();
break;
default:
// unrecognized function name.
}
You can optimize this by creating an array of function names, searching the array for the desired function name, then executing the value in the array. 您可以通过创建一个函数名称数组,在该数组中搜索所需的函数名称,然后执行该数组中的值来优化此功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.