gpt4 book ai didi

javascript - 将回调函数作为 html 数据属性传递

转载 作者:行者123 更新时间:2023-12-05 03:12:42 25 4
gpt4 key购买 nike

我创建了一个这样的 DOM 结构

<div data-execute="someFunction.abc" id="someId">
</div>

我能够在 js 中检索属性,但我打算将其作为回调函数执行。所以我是这样做的

var x = document.getElementById("someId").getAttribute('data-execute');

正如预期的那样,这将返回 someFunction.abc 。但是在安慰 typeof(x) 时它显示“string”。请引用这个 fiddle

var someFunction = function() {
alert("Hello")
}
var load = (function(module, global) {
var x = document.getElementById("someId").getAttribute('data-execute');
console.log(typeof(x))

}(load || {}, this))
<div data-execute="someFunction.abc" id="someId">
Some Function
</div>

我也检查了这个链接 Passing a Javascript function through inline data- attributes

但我无法将它作为回调函数来执行。任何帮助都将非常有用。

最佳答案

试试这个:

<div data-execute="someFunction.abc" id="someId"></div>

var x = document.getElementById("someId").getAttribute('data-execute');
window[x].call();

关于javascript - 将回调函数作为 html 数据属性传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32795225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com