how can i make a value from variable be a function name?
i created an exercise program that create a dynamic menu from 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.
开发者_StackOverflow社区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. 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();
where fname holds the value of the supposedly my function name. but everytime i run my program, an error message shows "fname is not a function". 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.? or a .html page inside it? 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. 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.
精彩评论