请检查以下代码。在模态开启输出值上显示类似于" NaN"直到我提供输入。但我想在输出上只显示空白字段,直到我提供任何输入。我怎样才能实现这一目标?可能吗?所有的快乐编码。请添加bootstrap和jquery来测试代码。感谢。
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<input type="text" name="" id="AmazonPrice" disabled="disabled" value="10"><br/>
<input type="text" name="" id="BreakEven" disabled="disabled" value="20"><br/>
<input type="text" name="" id="ComPrice" disabled="disabled" value="15"><br/>
Input:<input type="text" name="" id="YourPrice" value=""><br/>
Output:<input type="text" name="" id="YourProfit" value=""><br/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('#YourPrice').keyup(updatetxt);
$('#AmazonPrice').keyup(updatetxt);
function updatetxt() {
var YourPrice = $('#YourPrice').val();
var AmazonPrice = $('#AmazonPrice').val();
var BreakEven = $('#BreakEven').val();
var float_YourPrice = parseFloat(YourPrice);
var float_AmazonPrice = parseFloat(AmazonPrice);
var float_BreakEven = parseFloat(BreakEven);
$('#YourProfit').val(profitCalculation(float_AmazonPrice, float_BreakEven, float_YourPrice));
}
updatetxt();
function profitCalculation(AmazonPrice, BreakEven, YourPrice) {
var YourProfit = YourPrice - (YourPrice / 100 * BreakEven + 0.30) - AmazonPrice;
return YourProfit.toFixed(2);
}
</script>
</body>
</html>
答案 0 :(得分:1)
快速解决方案:如果是NaN
则插入条件检查,如果是,则返回空字符串。
// inside function profitCalculation
return isNaN(YourProfit) ? '' : YourProfit.toFixed(2);
isNaN
- https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN