admin管理员组文章数量:1135609
I was looking at to create a simple plugin for jQuery. Following the section about options and settings, I did the following, which didn't work (the script quit when it encountered the setting).
var settings = {
'location' : 'top',
'background-color': 'blue'
}
...
$this.css('backgroundColor', settings.background-color); // fails here
Once I removed the dash from the background color, things work properly.
var settings = {
'location' : 'top',
'backgroundColor': 'blue' // dash removed here
}
...
$this.css('backgroundColor', settings.backgroundColor);
Am I missing something, or are the jQuery docs wrong?
I was looking at http://docs.jquery.com/Plugins/Authoring#Defaults_and_Options to create a simple plugin for jQuery. Following the section about options and settings, I did the following, which didn't work (the script quit when it encountered the setting).
var settings = {
'location' : 'top',
'background-color': 'blue'
}
...
$this.css('backgroundColor', settings.background-color); // fails here
Once I removed the dash from the background color, things work properly.
var settings = {
'location' : 'top',
'backgroundColor': 'blue' // dash removed here
}
...
$this.css('backgroundColor', settings.backgroundColor);
Am I missing something, or are the jQuery docs wrong?
Share Improve this question edited Sep 18, 2017 at 5:27 user663031 asked Apr 1, 2011 at 16:22 maxtwoknightmaxtwoknight 5,3463 gold badges28 silver badges43 bronze badges 1 |5 Answers
Reset to default 154no. the parser will interpret it as the subtract operator.
you can do settings['background-color']
.
Change settings.background-color
to settings['background-color']
.
Variables cannot contain -
because that is read as the subtract operator.
You can do something like this:
var myObject = {
propertyOne: 'Something',
'property-two': 'Something two'
}
for (const val of [
myObject.propertyOne,
myObject['propertyOne'],
myObject['property-two']
]){
console.log(val)
}
Dashes are not legal in javascript variables. A variable name must start with a letter, dollar sign or underscore and can be followed by the same or a number.
You can have dashes in strings. If you really wanted to keep that dash, you'd have to refer to the property using brackets and whatnot:
$this.css('backgroundColor', settings['background-color']);
本文标签: Are dashes allowed in javascript property namesStack Overflow
版权声明:本文标题:Are dashes allowed in javascript property names? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736935626a1956936.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
background-color
as a property accessor, not as a variable. Variables can only be Identifiers, property accessor are less strict and can be IdentifierNames (ReservedWords are not excluded). But in this case,background-color
is neither Identifier nor IdentifierName. – Oriol Commented Mar 15, 2016 at 21:35