1

我对javascript很陌生,但我知道你可以调用一个函数,它由一个字符串表示,这样:

 var function_to_call = window[values['function']];
 //Where values['function']='functionName'

到目前为止一切顺利,那么我们有:

 if(typeof function_to_call == 'function'){
       if(values['parameters']!= '')
                function_to_call(values['parameters']);
       else function_to_call();
  };

当然,这是行不通的,因为参数以“parameter1,parameter2”的形式出现在一个字符串中,所以你最终得到

function_to_call("parameter1, parameter2");

而不是

function_to_call(parameter1, parameter2);

有任何想法吗?感谢您的时间!

扩展:

传递给函数的参数代表页面中元素的“id”;所以被调用的函数将尝试通过以下方式获取这些元素:

document.getElementById(parameter1);
...some other things...
document.getElementById(parameter2);
4

2 回答 2

3

我假设参数名称也代表全局变量。

如果是这样,您可以将它们拆分为一个数组,然后.map()将该数组拆分为相关全局变量的新数组。

然后使用.apply()参数数组调用函数。

if (typeof function_to_call == 'function') {
     if(values['parameters']!= '') {
          var args = values['parameters'].split(",")
                                         .map(function(name) {
                                             return window[name.trim()];
                                         });
          function_to_call.apply(window, args);
     } else function_to_call();
}

.trim()and方法将需要 IE8的.map()shim ... 但这主要显示了您如何做到这一点。作为替代方案,您可以传递一个正则表达式来.split()处理任何空间。

var args = values['parameters'].split(/\s*,\s*/)...
于 2013-06-14T00:35:13.510 回答
0
 if(typeof function_to_call == 'function'){
   if(values['parameters']!= '')
            setTimeout('function_to_call('.values['parameters'].');');
   else  setTimeout('function_to_call();',0);
  }
于 2013-06-14T00:34:18.727 回答