Accessing JavaScript Object Properties with Hyphens
When working with JavaScript, referencing object properties with a hyphen can be challenging. Consider the following scenario:
var style = css($(this)); alert(style.width); // Works fine alert(style.text-align); // Uncaught Reference Error
The hyphen in "text-align" is interpreted as a minus sign, leading to the error.
Solution 1: Camel Case Conversion
For CSS properties, using the camel case key notation is the preferred method:
obj.style-attr // Becomes obj["styleAttr"]
Solution 2: Key Notation
You can also use key notation instead of dot notation:
style["text-align"]
JavaScript allows you to refer to object properties using the same syntax as arrays:
arr[0] // Array index obj["method"] // Object property
Additional Considerations:
[a-zA-Z_$][0-9a-zA-Z_$]*
By utilizing these techniques, you can efficiently access JavaScript object properties containing hyphens.
The above is the detailed content of How to Access JavaScript Object Properties with Hyphens?. For more information, please follow other related articles on the PHP Chinese website!