当它不应该变成真时,它变成了真的
问题描述:
我有某种商店。 1条带过滤器,1条带物品。 过滤器栏具有输入字段起始和终止价格 它看起来像这样当它不应该变成真时,它变成了真的
<input id="pricefrom" type="text" placeholder="Min" style="position:relative; float: left; width:100px;">
<input id="priceto" type="text" placeholder="Max" style="position:relative; float: right; width:100px;">
而且脚本时用户集中的是处理输入:
$("#pricefrom").focusout(function() {
var from = $("#pricefrom").val();
var to = $("#priceto").val();
console.log("from: "+from);
console.log("to: "+to);
if(from > to){
$('#pricefrom').val(to);
from = to;
console.log("from > to");
}
drawItems(from, to);
});
$("#priceto").focusout(function() {
var from = $("#pricefrom").val();
var to = $("#priceto").val();
console.log("from: "+from);
console.log("to: "+to);
if(to < from){
$('#priceto').val(from);
to = from;
console.log("to < from");
}
drawItems(from, to);
});
如果用户把以上的价格大于TO,是使其成为均匀。输入“150-50”=>“150-150”
但它碰巧只能正常工作1次。然后例如它具有“200-200”值。我把从价格来纠正50的价值。它从“50”到“200”“从”到“”并且使得等于200.但是它更低,地狱(从>到)如何成为真实?
Sry英语差。
答
.val()
返回字符串,而不是数字,因此您正在执行词典对比,而不是数字比较。字符串"50"
大于"150"
。
在比较它们之前,将值转换为数字。
var from = parseInt($("#pricefrom").val(), 10);
var to = parseInt($("#priceto").val(), 10);
答
看起来像来自JavaScript的标准类型玩笑。比较两个示例:
50 > 200; // gives false
"50" > "200"; // gives true, because, "5" greater then "2"
.val()
返回一个字符串,所以您要比较字符串。比较之前调用parseInt
,应该从这样的错误预防:
var from = parseInt($("#pricefrom").val(), 10);
var to = parseInt($("#priceto").val(), 10);
附:永远不要忘记基数为parseInt
(在我们的例子中为10)。否则,如果在输入中有一些类似“023”的值(从0开始),一些浏览器可以将其理解为八进制数。
Daaamn,当然是。我听说过并忘记了。我是新来的编码,所以... 工作就像一个魅力。非常感谢你 – ikebastuz