首页 > 解决方案 > 为什么 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 封装每人的小费金额和每人的总额,并且当人员的输入值为空时不会出现。

标签: javascripthtmlcss

解决方案


问题是persons变成NaN,因为如果值留空,当它运行时""变成。NaNparseInt()

解决此问题的方法是将其默认为0如果该字段留空。

var persons = parseInt(document.getElementById("persons").value || 0);

推荐阅读