admin管理员组

文章数量:1193778

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?

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?

Share Improve this question edited Jan 3, 2013 at 15:34 Cerbrus 72.8k19 gold badges136 silver badges150 bronze badges asked Jan 3, 2013 at 15:25 KlaasvaakKlaasvaak 5,64416 gold badges48 silver badges68 bronze badges 4
  • Which technology are you using? PHP/jquery? Or is it a javascript only question? – Adder Commented Jan 3, 2013 at 15:29
  • how you want use that attribute? – VitVad Commented Jan 3, 2013 at 15:29
  • no, this way sure will not work. but according to your purpose you can use whatever you like. e.g. onblur, onclick, etc... what do you need exactly – mamdouh alramadan Commented Jan 3, 2013 at 15:31
  • I'm using Javascript. Creating my own components using Mozilla x-tag, which is Javacript. – Klaasvaak Commented Jan 3, 2013 at 15:44
Add a comment  | 

4 Answers 4

Reset to default 18

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!');
}

Using Webpack.

<div data-func="funcName"></div>
window.funcName = function() {};

Use eval:

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

Will show hello;

本文标签: javascriptPassing function with custom data attributeStack Overflow