Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
5
rated 0 times [  9] [ 4]  / answers: 1 / hits: 19398  / 10 Years ago, fri, december 12, 2014, 12:00:00

Is it possible to write an html attribute that will store the name of a javascript function and then extract that val() and execute that function? Example:



<button id=example data-function-name=showAllElements()>


and then in js/jq



fn = $('#example').data('function-name');

fn;

More From » jquery

 Answers
2

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.


[#68503] Wednesday, December 10, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marisela

Total Points: 103
Total Questions: 105
Total Answers: 102

Location: Solomon Islands
Member since Fri, Oct 8, 2021
3 Years ago
;