是否允许在JavaScript属性名称中使用破折号?
我在看http://docs.jquery.com/Plugins/Authoring#Defaults_and_Options为jQuery创建一个简单的插件。在关于选项和设置的部分之后,我做了以下操作,但无效(脚本在遇到设置时退出)。是否允许在JavaScript属性名称中使用破折号?
var settings = {
'location' : 'top',
'background-color': 'blue'
}
...
$this.css('backgroundColor', settings.background-color); // fails here
一旦我从背景颜色中删除短划线,事情就能正常工作。
var settings = {
'location' : 'top',
'backgroundColor': 'blue' // dash removed here
}
...
$this.css('backgroundColor', settings.backgroundColor);
我错过了什么,或者是jQuery文档错了吗?
变化settings.background-color
变为settings['background-color']
。
变量不能包含-
,因为它被读为减法运算符。
+1因为.. – 2012-02-23 21:21:33
你可以在字符串中有破折号。如果你真的想保持这种破折号,你不得不指使用括号和诸如此类的东西属性:
$this.css('backgroundColor', settings['background-color']);
破折号是不合法的JavaScript变量。变量名称必须以字母,美元符号或下划线开头,后面跟着相同或数字。
但这不是一个变量。 – 2017-09-18 05:28:00
请注意,您正在尝试使用'background-color'作为属性存取器,而不是作为变量。变量只能是标识符,属性访问器不太严格,可以是标识符名称(不包括保留字)。但在这种情况下,'background-color'既不是标识符也不是标识名。 – Oriol 2016-03-15 21:35:23