[英]How to execute string containing function name AND parameters?
In javascript, I have a string like this: 在javascript中,我有一个这样的字符串:
"doSomething('param1','param2')"
And I want to execute it. 我想执行它。 I am aware that I could normally use
我知道我通常可以使用
window['doSomething']('param1', 'param2');
But that only works if my function name is separate from the arguments. 但是只有当我的函数名与参数分开时才有效。 In my case they are already combined.
在我的情况下,他们已经合并。 I think I can use eval() but the consensus seems to be that it should be avoided.
我想我可以使用eval(),但共识似乎是应该避免。 Is there another way?
还有另外一种方法吗?
EDIT: To answer the request for more info: I am using this string like this: 编辑:要回答更多信息的请求:我使用这样的字符串:
<a id="YesButton" onclick="closeModalView_Yes("doSomething('param1','param2')")">
Where closeModalView_Yes will close the modal yes/no window and then execute the given function, although at times I may pass it doSomethingElse(param1) which only takes one parameter. 其中closeModalView_Yes将关闭模态是/否窗口,然后执行给定的函数,虽然有时我可能会传递doSomethingElse(param1),它只接受一个参数。
Use eval, just like: 使用eval,就像:
eval( "console.log( 'hey', 'here I am' )" );
However eval is pretty dangerous and it's not recommended. 然而, eval非常危险 ,不建议使用。
If you can (still we don't have much info about your case), render your JavaScript between <script>
tags in your template, making it a "regular code", much easier to debug. 如果可以(我们仍然没有太多关于您的情况的信息),请在模板中的
<script>
标记之间渲染JavaScript,使其成为“常规代码”,更容易调试。
Also a good practice is to pass data (ie with JSON) rather than code. 另一个好的做法是传递数据(即使用JSON)而不是代码。 Try rethinking your logic or provide additional information.
尝试重新考虑您的逻辑或提供其他信息。
<a id="YesButton" onclick="closeModalView_Yes("doSomething('param1','param2')")">
You really shouldn't pass that as a string, but as a function: 你真的不应该把它作为字符串传递,而是作为一个函数:
closeModalView_Yes(function(){ doSomething('param1','param2'); });
together with 和...一起
function closeModalView_Yes(callback) {
// do whatever needs to be done to close the window
// and after that
callback();
}
Btw, with your current approach the HTML is not even valid, it would need to be 顺便说一句,使用您当前的方法,HTML甚至不是有效的,它需要
<a id="YesButton" onclick="closeModalView_Yes("doSomething('param1','param2')")">
<!-- ^^^^^^ ^^^^^^ -->
You could've avoided that by registering the event via javascript instead of inline attributes. 您可以通过javascript而不是内联属性注册事件来避免这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.