Forum Moderators: open

Message Too Old, No Replies

Question on string replacement

         

ericazhj

5:13 pm on Mar 9, 2007 (gmt 0)

10+ Year Member



Hi,

In fact I am not sure if the title is proper. I will give you an example on my question:

Originally:

this.ajaxFunction();

I want to use:

var func_name="ajaxFunction()" ;

Then I want to call ajaxFunction() by use of the variable func_name. How could I do? I am new for Javascript. Is there some experts help me about it? Thanks.

Fotiman

6:01 pm on Mar 9, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




I want to use:

var func_name="ajaxFunction()" ;

Then I want to call ajaxFunction() by use of the variable func_name. How could I do?

You could assign the variable to contain the actual function itself. For example:

var func_name=ajaxFunction;

Note, no quotes, and no ().

Here's an example:


function ajaxFunction() {
alert("hello");
}
var func_name=ajaxFunction;
func_name();

Alternatively, you could use the eval function to evaluate the string into JavaScript code. For example:


function ajaxFunction() {
alert("hello");
}
var func_name="ajaxFunction()";
eval(func_name);

This method is slightly more costly though.