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

Passing function with custom data attribute

本文关键字:数据属性 函数 自定义      更新时间:2023-09-26

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

这不起作用:

<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对象的属性。

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

js:

var myfunction = $('#some').data('my-function');
if(myfunction != undefined){     
    eval("myfunction = "+myfunction, myfunction);    
}
if(typeof myfunction ==="function") {
    myfunction('Cristo Rabani!');
}

使用Webpack。

<div data-func="funcName"></div>
window.funcName = function() {};

使用eval:

eval("alert('hello');");

会打招呼;