How do I reference a javascript object property with a hyphen in it?

后端 未结 11 608
慢半拍i
慢半拍i 2020-11-22 06:07

Using this script to make a style object of all the inherited etc styles.

var style = css($(this));
alert (style.width);
alert (style.text-align);

相关标签:
11条回答
  • 2020-11-22 06:36

    Hyphenated style properties are referenced via camelCase in JavaScript, so use style.textAlign.

    0 讨论(0)
  • 2020-11-22 06:37

    EDIT

    Look at the comments you will see that for css properties key notation is not compatible with a number of properties. Using the camel case key notation therefore is the current way

    obj.style-attr // would become 
    
    obj["styleAttr"]
    

    Use key notation rather than dot

    style["text-align"]
    

    All arrays in js are objects and all objects are just associative arrays, this means you can refer to a place in an object just as you would refer to a key in an array.

    arr[0]
    

    or the object

    obj["method"] == obj.method
    

    a couple things to remember when accessing properties this way

    1. they are evaluated so use strings unless you are doing something with a counter or using dynamic method names.

      this means obj[method] would give you an undefined error while obj["method"] would not

    2. You must use this notation if you are using characters that are not allowed in js variables.

    This regex pretty much sums it up

    [a-zA-Z_$][0-9a-zA-Z_$]*
    
    0 讨论(0)
  • 2020-11-22 06:37

    The answer to the original question is: place the property name in quotes and use array style indexing:

    obj['property-with-hyphens'];
    

    Several have pointed out that the property you are interested in is a CSS property. CSS properties that have hyphens are automatically converted to camel casing. In that case you can use the camel cased name like:

    style.textAlign;
    

    However this solution only works for CSS properties. For example,

    obj['a-b'] = 2;
    alert(obj.aB);          // undefined
    alert(obj['a-b']);      // 2
    
    0 讨论(0)
  • 2020-11-22 06:39

    CSS properties with a - are represented in camelCase in Javascript objects. That would be:

    alert( style.textAlign );
    

    You could also use a bracket notation to use the string:

    alert( style['text-align'] );
    

    Property names may only contain characters, numbers, the well known $ sign and the _ (thanks to pimvdb).

    0 讨论(0)
  • 2020-11-22 06:42

    I think in the case of CSS styles they get changed to camelCase in Javascript so test-align becomes textAlign. In the general case where you want to access a property that contains non-standard characters you use array-style. ['text-align']

    0 讨论(0)
提交回复
热议问题