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
  • Note you are attempting to use 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
Add a comment  | 

5 Answers 5

Reset to default 154

no. 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