[英]how can i make a value from variable be a function name?
i created an exercise program that create a dynamic menu from json. 我创建了一个练习程序,从json创建一个动态菜单。 and then, everytime i clicked that dynamic menu, a tab will appear having a tab name depending on what is the name of the tab you are clicking.
然后,每次单击该动态菜单时,都会出现一个选项卡,其中包含选项卡名称,具体取决于您单击的选项卡的名称。
what i want now, that i'm still figuring out, is that everytime i clicked the menu, it will call a function which have the same name of the menu i clicked., but i just dont know how to do it. 我现在想要的,我还在想,是每次我点击菜单,它会调用一个与我点击的菜单名称相同的功能。但我只是不知道该怎么做。 my js functions is a separate file.
我的js函数是一个单独的文件。 here's the code:
这是代码:
....
$('.menu').click(function () {
dyna_tabs.add('Tab' + $(this).attr("rel"), //this is for the <a href= "-">
$(this).attr("rel"), //this if for the title
$(this).html()); // for the tab_content
fname = $(this).html(); // this is my variable name which i plan to use as function name
alert('this would be my function name ' + fname);
fname();
});
....
you can find the rest of the dynamic tab code here . 您可以在此处找到其余的动态选项卡代码。 i just did some edit that would create a menu then tab from the menu.
我只是做了一些编辑,从菜单中创建菜单然后选项卡。
so... i type fname();
所以...我输入
fname();
where fname holds the value of the supposedly my function name. 其中fname保存所谓的我的函数名称的值。 but everytime i run my program, an error message shows "fname is not a function".
但每次我运行我的程序时,错误消息显示“fname不是函数”。 can anybody here knows how to do this right?
这里的任何人都知道如何做到这一点吗? please....
请....
and one more thing, is anybody knows how put some html codes inside my dynamic tab.? 还有一件事,是否有人知道如何在我的动态标签中放置一些HTML代码。 or a .html page inside it?
或者里面的.html页面? thank you for reading
谢谢你的阅读
You can use another function that will call the necessary function. 您可以使用另一个将调用必要功能的函数。 Like:
喜欢:
loader(fname);
function loader(s) {
switch(s) {
case 'xy': xy(); break;
...
}
}
Your other option might be to store your functions in an object: 您的另一个选择可能是将您的函数存储在一个对象中:
var myFunctions={
'xy' : function () {
//do something here
},
...
};
and then you can call them easily like: 然后你可以轻松地称呼它们:
myFunctions[fname];
These are not complete solutions, just some guidelines that you could follow. 这些不是完整的解决方案,只是您可以遵循的一些指导原则。 The advantage over eval is that with these solutions it cannot happen that a function you have not intended to run could run.
优于eval的优势在于,使用这些解决方案,您无法运行的功能无法运行。 Only the predefined ones can be called.
只能调用预定义的。
I will apologize for this in advance. 我会事先为此道歉。
eval(fname + '()');
should work 应该管用
According to this question ( How to execute a JavaScript function when I have its name as a string ) there are some better alternatives. 根据这个问题( 当我将其名称作为字符串时如何执行JavaScript函数 )有一些更好的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.