We're using HTML5's data-*
attributes for some of our client side interaction set up. jQuery uses these to do its thing.
The catch is that the HTML coming in may vary. Obviously this is the problem that should be fixed but I'm not always in control of the HTML being produced, unfortunately.
The question:
Given these two tags:
<a data-sampleAttributeName="example">
<a data-sampleattributename="example">
Is there a clever way to treat them as one and the same?
The best I've come up with is something like this:
var theAttribute = ($myobject).data('sampleAttributeName');
if (($myobject).data('sampleAttributeName')){
theAttribute = ($myobject).data('sampleAttributeName')
} else {
theAttribute = ($myobject).data('sampleattributename')
}
I could turn that into a function that I could just pass the camelCase version to and check for both as well. I was just wondering if there was a cleaner built-in feature in jQuery to ignore the case of the data
(or attr
) value.
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
来源:https://stackoverflow.com/questions/7641551/have-jquery-ignore-case-in-attribute-data-names