-
-
Save shawnchin/701652 to your computer and use it in GitHub Desktop.
// return data-* attributes of a node as a dict | |
function getDataAttributes(node) { | |
var vstr = $().jquery.split("."); | |
var v0 = parseInt(vstr[0]) || 0, | |
v1 = parseInt(vstr[1]) || 0, | |
v2 = parseInt(vstr[2]) || 0; | |
// jQuery >= 1.4.4 has built in op to do this. | |
if ( v0 > 1 || (v0 == 1 && v1 > 4) || (v0 == 1 && v1 == 4 && v2 >= 4)) { | |
return node.data(); | |
} | |
// for jQuery < 1.4.4, work it out ourselves, | |
var d = {}, re_dataAttr = /^data\-(.+)$/; | |
$.each(node.get(0).attributes, function(index, attr) { | |
if (re_dataAttr.test(attr.nodeName)) { | |
var key = attr.nodeName.match(re_dataAttr)[1]; | |
d[key] = attr.nodeValue; | |
} | |
}); | |
// merge in data added/modified via $.fn.data (>1.4 only) | |
if (v0 == 1 && v1 == 4)) { $.extend(d, node.data()); } | |
return d; | |
} |
In addition to what Nick Craver said, I'm also curious as to why you're trying to create a version independent function, when one version of jQuery is every going to be used on a page (and most likely for the entire project). The overhead of including the additional function is not insignificant considering that one of the two will certainly never be used.
This is of course a moot point if you decide to not use jQuery.fn.data
because of the way it parses the attributes.
Related chat transcript: http://chat.stackoverflow.com/transcript/message/118676#118676
@NickCraver: Lacking experience with javascript, I was just being overly cautious. The worry I had at time of writing was that a straight forward string compare would be invalid once we get double digit version numbers, e.g. "1.10.1" or "1.4.10".
@ZhangYiJiang: I attempted to make it version independent as it's part of a plugin that I plan to use in different projects (one of which were developed against 1.4.2 and not tested with 1.4.4). However, I do see your point.
In retrospect, it does seem rather pointless to include both approaches when one would work for both pre/post 1.4.4 versions.
Many thanks.
I'd just do
if($.fn.jquery > "1.4.4")
since it's a string.