我正在构建一个小费计算器,但我无法使函数中的 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 输入值为空时出现。
最佳答案
函数 parseInt
返回 '从给定字符串解析的整数。如果第一个字符无法转换为数字,则返回 NaN
。
如果您提供一个空值 ('') 它将返回
NaN
不等于任何东西,甚至不等于它自己。
有几种方法可以解决这个问题:
- 使用
Number.isNaN(var)
检查它是否为 NaN - 使用像
var personsValue
这样的中间值并检查它是否等于空字符串 ''。 - 使用混合建议的解决方案并分配 0 虚假值的值('',未定义,n
等……)
关于javascript - 为什么 if 语句不起作用并使用显示 : none? 使我的元素消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55778485/