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

后端 未结 11 607
慢半拍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:21
    alert(style.textAlign)
    

    or

    alert(style["textAlign"]);
    
    0 讨论(0)
  • 2020-11-22 06:26

    Use brackets:

    var notTheFlippingStyleObject = {
        'a-b': 1
    };
    
    console.log(notTheFlippingStyleObject["a-b"] === 1); // true
    

    More info on objects: MDN

    NOTE: If you are accessing the style object, CSSStyleDeclaration, use must camelCase to access it from javascript. More info here

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

    To directly answer the question: style['text-align'] is how you would reference a property with a hyphen in it. But style.textAlign (or style['textAlign']) is what should be used in this case.

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

    To solve your problem: The CSS properties with hyphens in them are represented by JavaScript properties in camelCase to avoid this problem. You want: style.textAlign.

    To answer the question: Use square bracket notation: obj.prop is the same as obj["prop"] so you can access property names using strings and use characters that are forbidden in identifiers.

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

    The object property names are not one-to-one matches for the css names.

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

    At first, I wonder why the solution didn't work on my end

    api['data-sitekey'] //returns undefined
    

    ...later on figure out that accessing data attributes is different: It should be like this:

    var api = document.getElementById("some-api");
    api.dataset.sitekey
    

    Hope this helps!

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