by latchkey · 14y ago · 0 comments
Think of it this way, say you have a template that is putting some data into an element like this:
<button id="fooButton" data-key="1.400">Click me to edit something</button>
Now, using .data() to select the information out, will always return 1.4 instead of what you want, which is 1.400.
Edit, after the parent was edited to include the data attribute example:
You should update your post to clarify that you're talking about data attributes. That's a significant detail and shouldn't have been left out.
Now that you've clarified, jQuery does behave as you've stated, but it's not a bug. I can see how it could be unexpected behavior to some, but it's explicitly stated in the .data() documentation:
Every attempt is made to convert the string to a
JavaScript value (this includes booleans, numbers,
objects, arrays, and null) otherwise it is left as a
string. To retrieve the value's attribute as a string
without any attempt to convert it, use the attr() method.
http://api.jquery.com/data/#data2A string of "1.410" is not the same as a float of 1.41. Running "1.410" full-circle through data() corrupts the input string. When you have data that has been entered by a user, you can't guarantee that it's not something that will happen to autoconvert.
This behavior is totally broken and should never be used. It will work 99.95% of the time, then fail in bizarre ways when a user types in something magic. These are the worst bugs in the world to hunt down. This really shouldn't be in jquery.
I can see why they would do this. Having to parseInt all default values wouldn't be very jQuery-like.
1.410 === 1.41
<div id="test" data-foo="1.1">
$('#test').data('bar', '1.1');
typeof $('#test').data('foo'); // number
typeof $('#test').data('bar'); // string
If the data-foo value is user input, then converting it to a number might not be expected. E.g. <div data-emoticon="0.0" /> elem.data('foo', { 'a':1, 'b':2 });
elem.data('foo'); // Returns the object
Is certainly more desirable than: elem.attr('foo', { 'a':1, 'b':2 });
elem.attr('foo'); // Returns "[object Object]"