Is it possible passing 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 it's a string with the value "hello();" instead of the function. How to solve this?
To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written. In the above case setting article. dataset.
$('selector expression'). attr('name','value'); First of all, specify a selector to get the reference of an element and call attr() method with attribute name parameter. To set the value of an attribute, pass value parameter along with name parameter.
You could 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 function hello
is defined in the global scope, and as such, is a property of the window
object.
<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!');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With