javascript - 为什么 if 语句不起作用并使用 display: none 使我的元素消失?
问题描述
我正在构建一个小费计算器,但我无法使函数中的 if 语句正常工作,它只是跳到计算。
function calculate() {
var bill = parseInt(document.getElementById("bill").value);
var tip = parseInt(document.getElementById("tip").value) * .01;
var persons = parseInt(document.getElementById("persons").value);
if (bill == "" || tip == "") {
alert("Please enter value");
return;
};
if (persons == "" || persons <= 1) {
persons = 1;
document.getElementById("perPerson").style.display = "none";
} else {
}
let totalTipPer = (bill * tip) / persons;
let totalPer = (bill + (tip * 100)) / persons;
let totalTip = bill * tip;
let total = bill + (tip * 100);
totalTipPer = totalTipPer.toFixed(2);
totalPer = totalPer.toFixed(2);
total = total.toFixed(2);
totalTip = totalTip.toFixed(2);
document.getElementById("total-tip/person").innerHTML = totalTipPer;
document.getElementById("total-price/person").innerHTML = totalPer;
document.getElementById("total-tip").innerHTML = totalTip;
document.getElementById("total-price").innerHTML = total;
}
document.getElementById("calculate").onclick = function () {
calculate();
document.getElementById('results').style.display = 'block';
}
我希望 div 封装每人的小费金额和每人的总额,并且当人员的输入值为空时不会出现。
解决方案
问题是persons
变成NaN
,因为如果值留空,当它运行时""
变成。NaN
parseInt()
解决此问题的方法是将其默认为0
如果该字段留空。
var persons = parseInt(document.getElementById("persons").value || 0);
推荐阅读
- symfony - Symfony 4 抛出 UndefinedMethodException 异常
- sapui5 - SAPUI5 为选择元素添加描述/工具提示
- singleton - 单例中的 Monolog 实现
- vba - 我怎样才能宏Word字体
- c# - 如何在注销按钮上使用带有提交类型的 Font Awesome
- vbscript - asp 应用程序按钮无法正确执行并且不执行服务器调用
- amazon-web-services - 访问被拒绝在 s3 存储桶上公开图像
- typescript - “V”型不能分配给“V”型。[2719]
- asp.net-mvc - 使用 MVC 在加载时自动打开一个弹出窗口
- php - 使用 htaccess 从文档根目录重定向到文件夹