javascript - 为什么 if 语句不起作用并使用显示 : none? 使我的元素消失

标签 javascript html css

我正在构建一个小费计算器,但我无法使函数中的 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 不等于任何东西,甚至不等于它自己。

有几种方法可以解决这个问题:

  1. 使用 Number.isNaN(var) 检查它是否为 NaN
  2. 使用像 var personsValue 这样的中间值并检查它是否等于空字符串 ''。
  3. 使用混合建议的解决方案并分配 0 虚假值的值('',未定义,n

等……)

关于javascript - 为什么 if 语句不起作用并使用显示 : none? 使我的元素消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55778485/

相关文章:

javascript - $.each 循环 JSON 数据会降低浏览器速度

html - Schema.org <head> HTML 标记 : can I just use the meta tags?

javascript - SVG 高度缩放不符合预期

javascript - 如何在不给定高度的情况下使内容在 flexbox 中滚动?

HTML/CSS 隐藏表行(不工作)

javascript - 用户根据提示设置背景颜色和字体

javascript - append() 时无法按类获取元素

javascript - MVC 4操作链接弹出框确认删除?

html5 Canvas 元素和 svg

php - 只有当它包含关键字时,才使用 CSS 隐藏具有特定类名的某些 tr