变量在javascript语句 [英] variable in javascript statement
问题描述
如何在这个JavaScript语句中添加一个变量字符串?
其中name可以对应于任何有效的字符串,例如WebkitTransform或Moztransform等。
How does one add a variable string in this javascript statement? where name may correspond to any valid string , say WebkitTransform or Moztransform,etc
document.getElementById('test').style.VARIABLE_NAME = 'rotate(15deg)';
我的代码似乎不工作,当我将VARIABLE_NAME设置为WebkitTransform,我直接使用WebkitTransform,因为没有通过变量命名。
提前感谢:)
My code doesn't seem to work when i set the VARIABLE_NAME to WebkitTransform, but it works fine if I use WebkitTransform directly, as in without naming it via a variable. Thanks in advance :)
推荐答案
访问Javascript对象成员的方法有两种。
There are two ways to access members of a Javascript object.
点符号 ,其使用标识符来访问成员:
Dot notation, which uses an identifier to access the member:
obj.member;
括号符号,使用字符串访问成员:
Bracket notation, which uses a string to access the member:
obj['member']
后者使用字符串来定位成员,容易使用任何表达式。表达式的值将转换为字符串,因此它们是等价的:
The latter uses a string to locate the member and you can just as easily use any expression. The value of the expression will be converted to a string so these are equivalent:
obj[{}]
obj['[object Object]']
如果你的表达式已经是一个字符串, ,在你的case你的变量持有一个字符串,所以你可以做:
If your expression is already a string it will be used as is, and in your case your variable holds a string so you can just do:
document.getElementById('test').style[VARIABLE_NAME] = 'rotate(15deg)';
这篇关于变量在javascript语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!