如何间接引用 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
或window
?
最佳答案
使用方括号表示法:
this.dataset[tempVariable];
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
关于Javascript - 方法名称的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50069012/