javascript - 第二个 if 语句不起作用

标签 javascript

在下面的程序中,我使用了 3 个 if 条件,但是中间的 if 语句不起作用,最后一个 if 语句工作正常,当我再次将第三个 if 语句更改为第二个语句时,第二个语句无法正常工作。 第三个 if 语句工作正常

function calculate() {
    var quantity = document.getElementById("quantity").value;
    var price = document.getElementById("price").value;
    var discount = document.getElementById("discount").value;
    var tax = document.getElementById("tax").value;

    if((quantity && price ) != null) {
        amount = quantity * price;
        document.getElementById("amount").value = amount;
    } else {
        alert("price & tax required");
    }

    if(discount != null) {
        var discount_amount = (quantity*price*discount)/100;
        amount = (quantity*price) - discount_amount;
        document.getElementById("amount").value = amount;
    } else {
        document.getElementById("amount").value = quantity * price;
    }

    if(tax != null) {
        var tax_amount = (quantity*price*tax)/100;
        amount = (quantity*price) + tax_amount;
        document.getElementById("amount").value = amount;
    } else {
        document.getElementById("amount").value = quantity * price;
    }
}

最佳答案

input.value返回一个字符串,该字符串永远不会 null,但它可以是空字符串,例如 ''

空字符串在数字上下文中转换为零。如果不需要,您需要进行显式检查,例如

if (input.value === '') {
    return;
}

关于javascript - 第二个 if 语句不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49856815/

相关文章:

php - 在显示 HTML 之前检测搜索页面的 Ajax 请求何时返回 0 个结果

javascript - 检测 Silverlight 服务器端

javascript - 图像上传 - MVC 在 Bootstrap 模式中使用时返回 null

javascript - 使用 axios get 获取请求失败,状态代码为 403

javascript - document.createElement 文本字段长度

javascript - 剪切矩形未在响应式图表中调整大小

javascript - Quill文本编辑器使用JQuery创建后如何使用实例

javascript - 如何从数组中选择一个随机字符串并将其分配给一个变量?

javascript - 如何处理字符串以保留字符到最后一位数字?

javascript - 浏览器的后退前进按钮显示出奇怪的行为。历史.js