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
4 Answers
Reset to default 18You 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
版权声明:本文标题:javascript - Passing function with custom data attribute - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738456904a2087807.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论