have jQuery ignore case in attribute/data names?

好久不见. 提交于 2019-11-30 08:52:53

For both the variations given here you should get the value using

.data('sampleattributename')

The camel casing ( .data('sampleAttributeName')) is for when the attribute is like this:

<a  data-sample-attribute-name="something">Anchor</a>

Check this jsfiddle

For each element you're interested in, iterate over the object returned by .data() and update that element's jQuery data by toLowerCase()-ing the keys.

$('a').each(function ()
{
    var $this = $(this),
        data = $this.data(),
        kTemp;

    for (var k in data)
    {
        kTemp = k.toLowerCase();
        if (k !== kTemp)
        {
            $this.data(kTemp, data[k]).removeData(k);
        }
    }
});

I have a lot of legacy code that has data-attributes in the html. Some attributes contain dashes, and some have mixed case. In order to support w3c spec for html5 data- attributes, and the changes to $.data brought forth in jQuery 1.6, I made a function to transform data attribute name strings to their w3c equivalent; That means that attributes like 'data-fooBar' will be transformed to 'foobar' and 'data-foo-barBaz' would be transformed to 'fooBarbaz'. I needed something like this to add to my $.data() callers so I don't have to update existing html, which could involve database updates, and it would be a nightmare to find all of the data-attributes and update them to conform to the w3c spec. This function is designed specifically to be used in jquery library, and checks the jquery version, only replacing the dashes (+ camelcase) for jQuery version 1.6+ (all data-attributes will be converted to lowercase regardless of jQuery version). The function could easily be converted to work without jQuery.

Usage:

var html5data = $(this).data(w3cdatakey('foo-barBaz')); //same as $.data('fooBarbaz');

check out this fiddle: jsfiddle example

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