Danbuntu Danbuntu - 6 months ago 10
jQuery Question

using variables to call jquery functions

I need to be able to call functions in jquery based on a variable - like windowvarname in javascript. This is not a duplicate question because the other answer is for javascript and not jquery.

For example;

var name = 'test1';

function test1() {
alert('test1 called');
}

function test2() {
alert('test2 called');
}

name();


I want to do this so that I can dynamically call functions based on the results from an array.

I've been searching high and slow but I can seem to be able work this out.

Answer

A better approach will be to create a Module and store all your functions there with variable names as properties of that module.

var name = 'test1';

var func = {
    test1: function() {
        alert('test1 called');
    },
    test2: function() {
        alert('test2 called');
    },
    test3: function() {
        alert('test3 called');
    },
    test4: function() {
        alert('test4 called');
    },
    test5: function() {
        alert('test5 called');
    }
}

var array = ['test1', 'test2', 'test3', 'test4', 'test5'];

func[name]();
func[array[3]]();
func[array[array.length - 1]]();