Created
June 3, 2012 04:50
-
-
Save gibson042/2861953 to your computer and use it in GitHub Desktop.
Cautious conversion of data- attributes to numbers by jQuery.fn.data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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