Why is jQuery.data() modifying the HTML5 data-x attribute value?
I have just encountered some very disturbing behavior in jQuery 1.6.2 that I hope someone can explain. Given the following markup...
<div id="test" data-test=" 01">Test</div>
Can someone tell me why accessing the attribute through .data()
causes it to be parsed to an int?
var t = $("#test").data("test");
alert(t); // shows "1"
t = $("#test").attr("data-test");
alert(t); // shows " 01"
Of course I have proof on jsF开发者_如何学编程iddle of this behavior.
From the doc for data(key)
:
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.
Since your example string CAN be converted to a number, it is.
Edit: As Joseph points out, this only applies when reading data straight from the element, like you're doing in this example. If you could set it first (i.e. data(key,value)
before reading), then the behavior disappears. The getter, when reading from the actual DOM element, performs type coercion.
jQuery people say:
As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.
Every attempt is made to convert the string (html5 data attribute value) 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.
From this page: http://api.jquery.com/data/
To add to Paul Equis's answer,
If you want to access it as a string, use the .attr()
method.
var t = $("#test").attr("data-test");
Edit: here's a demonstration showing one of the benefits of jQuery interpreting the data attribute.
http://jsfiddle.net/FzmWa/1/
精彩评论