You can, yes. Whether you should is another question entirely, to which the answer is almost certainly "no" (in terms of executing the string; in terms of the alternative shown below, there are times it's useful).
The way you'd evaluate that snippet of code (what you have isn't just a function name, because of the ()
) would be to use the dreaded eval
:
eval(fn);
There's almost always a better option than using eval
. (See below.)
eval
example:
$("#example").on("click", function() {
var fn = $("#example").attr("data-function-name");
eval(fn);
});
function showAllElements() {
alert("showAllElements was called");
}
<button type="button" id="example" data-function-name="showAllElements()">Click Me</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
One of the better options is to store your function references as properties on an object, and then use brackets notation to get the function reference based on the function name:
Example:
var functions = {
showAllElements: function() {
alert("showAllElements was called");
}
};
$("#example").on("click", function() {
var fn = $("#example").attr("data-function-name");
functions[fn]();
});
<button type="button" id="example" data-function-name="showAllElements">Click Me</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Note that there, I'm just storing the function name, not arbitrary code.
Update: See canon's answer for a clever way to handle it if you have your functions nested inside an object, e.g. mumble.foo.doSomething
, using reduce
. (reduce
is an ES5 feature, but it's polyfillable.)
Side note: Unless you're doing something more than just retrieving the value of a data-*
attribute, don't use data
, use attr
. data
initializes a data cache for the element, reads in all of the data-*
attributes for that element, and copies them to cache. If you're not using it, there's no reason to do that. The idea that you use data
to access data-*
attributes is a common misconception.