是否可以传递具有自定义数据属性的函数?
这不起作用:
<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
object.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)