Jquery .attr(attrname) doesn't always work?
I have to get an attribute value in a js s开发者_如何转开发cript. While I was using the Jquery method elem.attr() to retrieve that value,I noticed that in some case, that method doesn't work. For example:
<li value="1409079461">
If I call $(this).attr("value") on this element, it returns the right value,but
<li value="100001794127456">
If I call the method on this last element, that has an attribute with more digits, .attr("value") returns 0.
Does anyone know the reason of this strange behaviour? Is there a limit on the amount of data that the method can handle?
value of LI
is integer, and max integer is 2,147,483,647, everything else will be 0
I did not know but I checked in W3C recommendations and seems like <li/>
nodes can have value
attribute which should be a number as described here, but it is marked as deprecated. So as others (@Ivanov and @Digbyswift) mentioned it will be converted to a number.
I've checked an example code with jsFiddle, here and it's actually working in Safari, but I won't use value
attribute if you don't really need to.
I don't know why it doesn't work.
However it isn't valid HTML.
If you use data attributes it will work: http://jsfiddle.net/f75LT/
<ul>
<li data-value="1409079461">Test1</li>
<li data-value="100001794127456">Test2</li>
</ul>
$(document).ready(function() {
$('li').click(function() {
console.log($(this).data('value'));
});
});
jQuery is attempting to convert the value to an integer, tha value is too large and it is defaulting to zero.
If you need this value, then I would suggest placing an underscore character at the beginning to force jQuery to consider this a string. You can then strip the underscore afterwards.
精彩评论