简体   繁体   English

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

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

I am quite new to javascript, but I know you can call a function with it being represented by a string such that: 我对javascript很新,但我知道你可以调用一个函数,它由一个字符串表示,这样:

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

So far so good, then we have: 到目前为止,我们有:

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

Of course, this won´t work because the parameters come out as "parameter1, parameter2" all in one string so you end up with 当然,这不起作用,因为参数在一个字符串中都以“parameter1,parameter2”形式出现,所以你最终得到了

function_to_call("parameter1, parameter2");

rather than 而不是

function_to_call(parameter1, parameter2);

any ideas? 有任何想法吗? Appreciate your time! 感谢你的时间!

EXPANDED: 扩展为:

The parameters passed to the function represent the "id" of elements in the page; 传递给函数的参数表示页面中元素的“id”; so the function that is called will be trying to get those elements by doing: 所以调用的函数将尝试通过执行以下操作来获取这些元素:

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

I assume the parameter names represent global variables as well. 我假设参数名称也代表全局变量。

If so, you could split them into an Array, then .map() the Array into a new array of the related globals. 如果是这样,你可以将它们分成一个数组,然后将.map()数组转换成相关全局变量的新数组。

Then use .apply() to invoke the function with the array of arguments. 然后使用.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();
}

The .trim() and .map() methods will need a shim for IE8... but this mainly shows how you could do it. .trim().map()方法将需要IE8的垫片......但这主要说明了如何做到这一点。 As an alternative, you could pass a regex to .split() to take care of any spaces. 作为替代方案,您可以将正则表达式传递给.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