是否可以传递具有自定义数据属性的函数?
这不起作用:
<div data-myattr="hello();">
</div>
function hello(){
console.log('hello');
}
当我得到属性时,它是一个值为“hello();”的字符串而不是功能。如何解决?
最佳答案
你可以这样做:
<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.
}
这是有效的,因为函数 hello
是在全局范围内定义的,因此是 window
对象的属性。
关于javascript - 传递具有自定义数据属性的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14141860/