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

时间:2015-09-26 08:39:09

标签: javascript

我已经创建了像这样的DOM结构

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

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

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

正如预期的那样,这将返回someFunction.abc。但是在安慰typeof(x)时它显示&#34; string&#34;。请参考这个小提琴

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

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

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

但是我无法将其作为回调函数执行。任何帮助都会非常明显。

2 个答案:

答案 0 :(得分:1)

试试这个:

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

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

答案 1 :(得分:1)

您可以在全局范围中定义的函数中使用call方法,您可以在全局窗口ojbect中访问它。

价:

  

call()方法调用一个给定此值的函数   论据单独提供。

我假设代码在传递给函数之后是一个参数。

代码:

var someFunction = function (p) {
    alert(p)
}
var load = (function (module, global) {
    var x = document.getElementById("someId").getAttribute('data-execute');
    window[x.split('.')[0]].call(undefined, x.split('.')[1]);

}(load || {}, this))

演示:https://jsfiddle.net/IrvinDominin/5bjsmu3x/

相关问题