I’d like to call functions I’ve defined within the document ready function of jQuery, but am having a bit of trouble. I have the following code:
jQuery(document).ready( function($) {
function test1() {
alert('test1');
}
function test2() {
alert('test2');
}
var test_call = '2';
var fn = 'test' + test_call;
// use fn to call test2
});
I don’t want to use eval, and window[fn] doesn’t seem to be working. The two test functions don’t appear to be indices in the window variable. I appreciate the help and knowledge.
All I can think of that doesn’t use
eval()or some form of eval (passing a string tosetTimeout()is a form ofeval()), is to register the relevant function names on an object and then look up the function name on that object:or the registration could be done in the definition of the functions. If they were global functions, they would be implicitly registered on the
windowobject, but these are not global as they are scoped inside the document.ready handler function:Or, you could move the functions to the global scope so they are automatically registered with the window object like this: