Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Cautious conversion of data- attributes to numbers by jQuery.fn.data
// limit .data number parsing to canonical representations
// fixes jQuery tickets #7579; #11297; #10174
(function( $ ) {
var fnData = $.fn.data;
$.fn.data = function( key, value ) {
if ( value === undefined ) {
// parse data attributes on every element (including forms with unfortunately-named controls)
// before the official jQuery.fn.data gets a chance to
this.each(function() {
var attributes, idx, attrName, attrKey, attrValue,
data = $.data( this );
// make sure this is an element that hasn't been previously processed
if ( ( this.nodeType === 1 || this.nodeType && this.nodeType.nodeType === 1 ) &&
!data["fix #7579; #11297; #10174"] ) {
// deal with all data- attributes
attributes = this.attributes;
for ( idx = attributes.length - 1; idx >= 0; idx-- ) {
attrName = attributes[ idx ].name;
if ( (attrKey = /^data-(.*)/.exec( attrName )) != null ) {
attrKey = $.camelCase( attrKey[1] );
// set the data for this key unless it already exists (cf. dataAttr)
if ( data[ attrKey ] === undefined ) {
attrValue = attributes[ idx ].value;
try {
attrValue = attrValue === "true" ? true :
attrValue === "false" ? false :
attrValue === "null" ? null :
// here's the change
$.isNumeric( attrValue ) && +attrValue + "" === attrValue ? +attrValue :
/^(?:\{.*\}|\[.*\])$/.test( attrValue ) ? $.parseJSON( attrValue ) :
attrValue;
} catch( e ) {}
// storing the data
$.data( this, attrKey, attrValue );
}
}
}
// flag to skip parsing on the next .data request
$.data( this, "fix #7579; #11297; #10174", true );
}
});
}
// now defer to the original .data
return fnData.apply( this, arguments );
};
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment