使用自定义数据属性传递函数 [英] Passing function with custom data attribute

查看:195
本文介绍了使用自定义数据属性传递函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible passing a function with a custom data attribute?

这不起作用:

<div data-myattr="hello();">
</div>





function hello(){
    console.log('hello');
}

当我得到属性时,它是一个值为hello(); 而不是功能。如何解决这个问题?

When I get the attribute it's a string with the value "hello();" instead of the function. How to solve this?

推荐答案

你可以这样做:

<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 在全局范围内定义,因此是窗口对象的属性。

This works because the function hello is defined in the global scope, and as such, is a property of the window object.

这篇关于使用自定义数据属性传递函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆