...">

Pass with user data attribute

Is it possible to pass a function with a custom data attribute?

This does not work:

<div data-myattr="hello();"> </div> 
 function hello(){ console.log('hello'); } 

When I get the attribute, this is a string with the value "hello ();" instead of function. How to solve this?

+4
source share
3 answers

You can do it as follows:

 <div data-myattr="hello"></div> 
 function hello(){ console.log('hello'); } function executeFunctionFromData(){ var d = 'hello' // Save `data-myattr` to d; (Obviously, this is just a hardcoded value as an example) window[d](); // Execute the function. } 

This works because the hello function is defined in the global scope and as such is a property of the window object.

+12
source
 <div id='some' data-my-function="function(x){console.log(x);}"></div> 

JS:

 var myfunction = $('#some').data('my-function'); if(myfunction != undefined){ eval("myfunction = "+myfunction, myfunction); } if(typeof myfunction ==="function") { myfunction('Cristo Rabani!'); } 
+6
source

Use eval:

 eval("alert('hello');"); 

Will show hi

0
source

All Articles