javascript - Javascript - 方法名称的变量?
问题描述
如何间接引用 javascript 对象?
认为:
<div id="foo" data-munchy="bar" data-crunchy="baz">FooBar</div>
<script>
document.getElementById("foo").onclick = function() {
tempVariable = 'munchy';
console.log(this.dataset.tempVariable);
}
</script>
我怎样才能访问this.dataset.{someVariable}
?在这种情况下,this.dataset.tempVariable
只能使用eval
orwindow
吗?
解决方案
使用方括号表示法:
this.dataset[tempVariable];
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
推荐阅读
- windows - 如何防止使用 GetTempFileName 创建的文件在重新启动时被自动删除
- python - 仅当其字符串值不为空时才将字典项添加到集合中的快捷方式?
- angular - 创建新日期时对象 Date() 出错
- xcode - 设置自定义时间以允许 NSLocalNotif xcode
- xaml - UWP“复合”绑定(绑定 Data.Name 而不是 Name)
- ruby-on-rails - Ruby on Rails - 设计 - 删除后用户有 :email 字段
- python - Python Dash web-app 引发内部服务器错误
- python - 搜索大型 csv
- php - Drupal 8 表单无法加载
- c# - 应用程序抛出 OutofMemoryException