传递具有自定义数据属性的函数
Passing function with custom data attribute
是否可以传递具有自定义数据属性的函数?
这不起作用:
<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');");
会打招呼;
相关文章:
- 序列化数据属性中对象的最可靠方法
- jQuery最近父级的数据属性选择器
- delete在Object上效率低下,但在DOM Element's的数据属性,与null out相比
- 数据属性仅在切换设备模式下工作
- 函数jquery.html()不提供数据属性集值
- 从 Bootstrap Typeahead 中的数据属性中调用函数
- 将数据属性从锚点元素传递到jQuery函数
- 调用自定义数据属性中的函数
- 通过内联数据属性传递Javascript函数
- JQuery从单击函数中检索数据属性
- 使用数据属性在一个函数中Jquery多个选择器
- 在下面的场景中,如何在$.ajax()函数的数据属性中发送参数
- 如何在fancybox2回调函数中读取数据属性
- 将回调函数作为html数据属性传递
- 创建一个切换数据*属性的jQuery函数
- jquery更多点击函数使用数据属性
- 使用多个值在一个jquery过滤函数中的数据属性的例子
- 传递具有自定义数据属性的函数
- jQuery:为每个点击函数添加多个数据属性
- 如何使用find()函数根据数据属性查找元素