使用自定义数据属性传递函数

Kla*_*aak 6 javascript html5

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

这不起作用:

<div data-myattr="hello();">
</div>
Run Code Online (Sandbox Code Playgroud)
function hello(){
    console.log('hello');
}
Run Code Online (Sandbox Code Playgroud)

当我得到属性时,它是一个值为"hello();"的字符串.而不是功能.怎么解决这个?

Cer*_*rus 13

你可以这样做:

<div data-myattr="hello"></div>
Run Code Online (Sandbox Code Playgroud)
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.
}
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为函数hello是在全局范围内定义的,因此是window对象的属性.

  • 好的解决方案 - 使用"eval"等替代品让我感到寒意. (2认同)

Cri*_*ani 5

<div id='some' data-my-function="function(x){console.log(x);}"></div>
Run Code Online (Sandbox Code Playgroud)

JS:

var myfunction = $('#some').data('my-function');

if(myfunction != undefined){     
    eval("myfunction = "+myfunction, myfunction);    
}

if(typeof myfunction ==="function") {
    myfunction('Cristo Rabani!');
}
Run Code Online (Sandbox Code Playgroud)