2011-04-01 147 views
42

我在看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文档错了吗?

+0

请注意,您正在尝试使用'background-color'作为属性存取器,而不是作为变量。变量只能是标识符,属性访问器不太严格,可以是标识符名称(不包括保留字)。但在这种情况下,'background-color'既不是标识符也不是标识名。 – Oriol 2016-03-15 21:35:23

回答

83

没有。解析器会将其解释为减法运算符。

你可以做settings['background-color']

+1

我明白了。谢谢,这是我应该使用的。 $ this.css('backgroundColor',options ['background-color']); – xecaps12 2011-04-01 16:33:15

+5

必须接受这个答案,因为它是正确的,并且在评论中包含这种诙谐的笑话。 – xecaps12 2011-04-01 17:06:12

+0

非常感谢这@dan! – 2016-09-15 19:38:54

13

变化settings.background-color变为settings['background-color']

变量不能包含-,因为它被读为减法运算符。

+0

+1因为.. – 2012-02-23 21:21:33

3

你可以在字符串中有破折号。如果你真的想保持这种破折号,你不得不指使用括号和诸如此类的东西属性:

$this.css('backgroundColor', settings['background-color']); 
8

破折号是不合法的JavaScript变量。变量名称必须以字母,美元符号或下划线开头,后面跟着相同或数字。

+0

但这不是一个变量。 – 2017-09-18 05:28:00

相关问题