来自“大于"的意外结果.文本输入值的比较 [英] Unexpected result from "greater than" comparison of values from a text input
问题描述
在尝试确定一个值是否大于另一个值时,我遇到了一个奇怪的JavaScript/jQuery数学错误.
I'm experiencing a strange JavaScript/jQuery math bug when trying to determine whether one value is greater than another.
以下是使用jsFiddle到我的代码的链接: http://jsfiddle.net/qxeTj/
Here is a link, using jsFiddle, to my code: http://jsfiddle.net/qxeTj/
$("#Quantity").live("focusout", function() {
var qty = +$(this).val();
var stock = +$('#StockLvl').val();
if (qty > stock) {
$('#Result').html("<p>Quantity: " + qty + "</p><p>Stock: " + stock + "</p>" + "<p>Not Enough Stock.</p>");
}
else if (stock > qty || stock == qty) {
$('#Result').html("<p>Quantity: " + qty + "</p><p>Stock: " + stock + "</p>" + "<p>Enough Stock.</p>");
}
});
问题示例:
当我将焦点放在input
字段之外时,如果它的值是1
或2
,则可以正常工作.如果我的值为3, 4, 5, 6, 7, 8, 9
,它甚至可以工作.
When I focus out of the input
field, if it has a value of 1
or 2
, it works fine. It even works if I have a value of 3, 4, 5, 6, 7, 8, 9
.
但是问题是当我使用10-19
或100-199
或1000-1999
等中的值时.它说它应该有足够的库存.
But the problem is then when I use values from 10-19
or 100-199
or 1000-1999
and so forth. It say's it has enough stock when it shouldn't.
推荐答案
您正在比较字符串.首先将它们转换为数字.
You're comparing strings. Convert them to numbers first.
var qty = Number( $(this).val() );
var stock = Number( $('#StockLvl').val() );
或
var qty = +$(this).val();
var stock = +$('#StockLvl').val();
或
这种方式对您而言最安全.
This way will be safest in your case.
var qty = parseInt( $(this).val(), 10 );
var stock = parseInt( $('#StockLvl').val(), 10 );
这篇关于来自“大于"的意外结果.文本输入值的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!