jQuery's data()
method will give you access to data-*
attributes, BUT, it clobbers the case of the attribute name. You can either use this:
$('#myButton').data("x10") // note the lower case
Or, you can use the attr()
method, which preserves your case:
$('#myButton').attr("data-X10")
Try both methods here: http://jsfiddle.net/q5rbL/
Be aware that these approaches are not completely equivalent. If you will change the data-*
attribute of an element, you should use attr()
. data()
will read the value once initially, then continue to return a cached copy, whereas attr()
will re-read the attribute each time.
Note that jQuery will also convert hyphens in the attribute name to camel case (source -- i.e. data-some-data == $(ele).data('someData')
). Both of these conversions are in conformance with the HTML specification, which dictates that custom data attributes should contain no uppercase letters, and that hyphens will be camel-cased in the dataset
property (source). jQuery's data
method is merely mimicking/conforming to this standard behavior.
Documentation
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…