0

I have the following scenario where I need to call a function based on the data attributes of the html element.

function func1(arg1){
    alert("func1");
}

function func2(arg2){
    alert("func2");
}

jQuery(document).on('click', '.func-class', function(){
  var funcName = jQuery(this).data('func-name');
  var funcArg = jQuery(this).data('func-arg');      
  //Need to call funcName(funcArg) here
});

HTML:

<div data-func-name="func1" data-func-arg="arg1" class="func-class">Func1</div>
<div data-func-name="func2" data-func-arg="arg2" class="func-class">Func2</div>

JSFiddle of the same: http://jsfiddle.net/E4HeT/

3 Answers 3

4

If those functions are defined in ths global scope, you can do this:

window[funcName](funcArg);

Otherwise, I would suggest putting them in an object like so:

var functions = {
    "func1":func1,
    "func2":func2
};
functions[funcName](funcArg);

This second one is actually safer, as it helps prevent arbitrary code execution.

Sign up to request clarification or add additional context in comments.

Comments

0

you can do like the following this

window[funcName](funcArg)

but you will have to get the reference of the function by setting it in a object for example (like what i did in the window object) because its private in the jQuery.ready function

Comments

0
$('.func-class').click(function(){

    var toCallArg = $(this).data('func-arg');        
    var toCall = function(toCallArg){            
        //your code
    };
    toCall(toCallArg);
});    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.