jquery returns 0 when reading a negative from value in IE
I'm new to jQuery, and stumbled across some unexpected results today. When selecting the value from an LI element using jquery, IE will return a 0 if the value is negative instead of the correct value. In Chrome, the code below will throw up an alert with a -1, but in IE it says 0. Any thoughts?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<script>
$开发者_JS百科(function () {
$(".ui-selected", this).each(function () {
alert(this.value);
});
});
</script>
<ol>
<li class="ui-selected" value="-1" />
</ol>
</body>
</html>
Not sure about the reason, however value is not an attribute of list item elements. If you need a custom value use a data-value
attribute (or other).
See this example for more information jsfiddle
<ul>
<li value="-1" data-value="-1"></li>
</ul>
$('li').each(function(){
alert(this.value); // 0
alert($(this).attr('data-value')); // -1
})
You're not really using jQuery to get the value. I don't know why IE is behaving that way, but I'd say give it a try using the native .attr()
, orgetAttribute
to get the value.
alert( $(this).attr('value') );
alert( this.getAttribute('value') );
@Josiah Ruddell noted that .attr()
didn't work.
EDIT: don't use 'value' use any other attribute name. See the updated working example here
Even if "value"
isn't a valid HTML attribute jQuery doesn't recognize this and its attribute selectors work just fine.
There isn't such a thing as an invalid selector. It either returns something or doesn't.
<ul>
<li class="ui-selected" myVar="-1" >
Hi
</li>
</ul>
$(".ui-selected").each(function(){
var liValue = $(this).attr('myVar');
var intVal = parseInt(liValue);
// Just to be safe you've retrieved only an integer!
alert(liValue);
});
精彩评论