Reputation: 27
I'm already aware that there's a similar question about this but seems cant make it to work.
Please let me know what needed to do.
example: ( where the string "test" is the function name )
<script>
function test(){
alert("Hello World");
}
//is this the right way to call it?
window["test"]();
</script>
//no eval pls
Upvotes: 0
Views: 60
Reputation: 1075
Please look in to following
var fn = window["test"];
if(typeof fn == 'function') {
fn();
}
Upvotes: 1
Reputation: 525
Pawan's answer is right, it doesn't work in fiddle because fiddle wraps code into $(window).on("load") event. Try it in normal page. Sorry, can't coment, low reputation
Upvotes: 0
Reputation: 1
Your example should work. Here is is an answer to a similar question How to execute a JavaScript function when I have its name as a string
Upvotes: 0
Reputation: 9947
try like this
<script>
function test(){
alert("Hello World");
}
var func = 'test'
this[func]();
</script>
Upvotes: 0
Reputation: 738
Eval is what you need. Example:
<script>
eval("alert('hello')");
</script>
Upvotes: 0