Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing function with custom data attribute

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?

like image 571
Klaasvaak Avatar asked Jan 03 '13 15:01

Klaasvaak


People also ask

How do you give a data attribute?

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.

How pass data attribute value in jQuery?

$('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.


2 Answers

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.

like image 136
Cerbrus Avatar answered Sep 22 '22 18:09

Cerbrus


<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!');
}
like image 35
Cristo Rabani Avatar answered Sep 22 '22 18:09

Cristo Rabani