繁体   English   中英

Javascript调用函数作为字符串,多个参数不使用eval()

[英]Javascript call function as string, with multiple parameters not using eval()

我对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);

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

如果是这样,你可以将它们分成一个数组,然后将.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().map()方法将需要IE8的垫片......但这主要说明了如何做到这一点。 作为替代方案,您可以将正则表达式传递给.split()来处理任何空格。

var args = values['parameters'].split(/\s*,\s*/)...
 if(typeof function_to_call == 'function'){
   if(values['parameters']!= '')
            setTimeout('function_to_call('.values['parameters'].');');
   else  setTimeout('function_to_call();',0);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM