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

后端 未结 11 746
慢半拍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: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
    

提交回复
热议问题