jQuery camel-case mapping from “data-” attribute names to “.data()” keys

后端 未结 1 604
小蘑菇
小蘑菇 2021-01-03 22:54

If you put a \"data-\" attribute on an element:

then you can get the value via the jQuery \".data()

相关标签:
1条回答
  • 2021-01-03 23:34

    You're right. The issue seems to be with the regex they use for conversion from camelCase to dashed.

    rmultiDash = /([a-z])([A-Z])/g;
    

    ...as used here:

    var name = "data-" + key.replace( rmultiDash, "$1-$2" ).toLowerCase();
    

    ...which results in:

    data-image-xoffset
    

    ...instead of:

    data-image-x-offset
    

    Demo: http://jsfiddle.net/TLnaW/

    So when you use the dashed version, when it looks for an attribute, it finds it with no need for a conversion, and then adds the camelCase version to the elements data in jQuery.cache.

    Subsequent attempts will then work because the correct camelCase is now there, so it no longer attempts to get it as an attribute, and therefore no longer needs the faulty regex.

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