Call function inside user data-attr?

Given the current CMS we work with, I need to call functions in a user data attribute. Is it possible to call the contents of a data attribute as a function to run, as shown below? A simple example:

Set

 <button data-function="alert('hello world')">Run Function</button>

Run

$('button').attr('function');

I believe that the above simply receives the content and actually does nothing when writing.

Is it possible?

+4
source share
4 answers

You can create Functionfrom the data attribute:

// create
var funcStr = $('button').data('function');
var f = new Function(funcStr);

// invoke
f();

See MDN

+3
source

If you want to execute the code, you need to call eval. You also need to use the fully qualified attribute name or use .data().

eval($('button').attr('data-function'));

or

eval($('button').data('function');
+1
source

eval.

eval($('button').attr('data-function'));
+1

, .

     $(document).ready(function() {
       $('button').click(function() {
         var functionObject = JSON.parse($('button').attr('data-function'));
         window[functionObject.name].apply(window, functionObject.arguments);
       });
     });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button data-function='{"name": "alert", "arguments" : ["hello world"]}'>Run Function</button>
Hide result

It parses the JSON string from the attribute data-function. Call the function provided nameusing the window object (excluding eval) and passing the arguments (inside the array) to the function with apply.

+1
source

All Articles