How to preserve the case of a data attribute?

三世轮回 提交于 2019-12-08 14:30:20

问题


The html object:

 <div data-myAttribute="test"></div>

The code:

 var $o = $("div");

 $.each($o.data(),function(k,v){
    console.log(k); 
    //writes 'myattribute' instead of 'myAttribute'
 });

How do I preserve the case of the attribute?


回答1:


If your goal is to target myAttribute as key of dataset property, you should use data-my-attribute:

<div data-my-attribute="test"></div>

See following link regarding camelCased rule: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset

PS: as Izkata commented it:

For reference for others, jquery also does conversion such that $div.data('my-attribute') returns the same thing as $div.data('myAttribute'). The vanilla javascript dataset property does not do this.




回答2:


Valid HTML data attributes can't contain uppercase characters anyway:

From the W3:

A custom data attribute is an attribute in no namespace whose name starts with the string "data-", has at least one character after the hyphen, is XML-compatible, and contains no characters in the range U+0041 to U+005A (LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z).




回答3:


You can't. Attribute names are always lowercase in HTML5.




回答4:


As an addendum to @A. Wolff's answer, you can apply a -- to the data attribute name if you want leading capitals.

<div data--my-attribute="test"></div>

Will result in a data key of MyAttribute



来源:https://stackoverflow.com/questions/27359388/how-to-preserve-the-case-of-a-data-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!