javascript - 传递具有自定义数据属性的函数

标签 javascript html

是否可以传递具有自定义数据属性的函数?

这不起作用:

<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/

相关文章:

javascript - 即使安装了 Node,也无法在 Node 中加载 Axios

html - 对 `htmlcxx::HTML::ParserDom::parseTree(std::string const&)' 的 undefined reference

javascript - HTML:td-iframe 位于表格内。它可以在空白处显示在外面吗?

html - 标题位置上的图像在 chrome 中带有边框并且在 firefox 中运行良好

javascript - 像 facebook IOS 应用程序一样的 CSS 动画菜单

javascript - 如何将 kendoMultiSelect 选定的值存储在数组变量中?

javascript - 在我的应用程序中使用 webpack 并且不能使用 javascript 的 typeof 指令

css - HTML5 + CSS 和设置 <HEADER> 的宽度

javascript - 如何动态更新道场树数据

javascript - 在原始 div 之前具有相同名称的 div id