首页 > 解决方案 > JavaScript 返回所有警报而不是一个。我该如何解决?

问题描述

所以,我正在尝试在 JS 中增强我的小费计算器应用程序。如果没有附加值,我决定在每个表单下方添加一个警报,不幸的是它部分不起作用。我有 3 种表格(账单金额,选择用户想要以百分比给出的小费类型以及有多少人共享账单。问题是,尽管只缺少一两个值,但 JS 会启动所有三个警报。另外,我想知道如何摆脱警报,因为即使在将所有值添加到计算器后仍然存在这些警报。它在添加 alert1、alert2 和 alert3 之前工作。

const calculateTip =() => {
    const cost = document.querySelector('.amount').value;
    const service = document.querySelector('.service').value;
    const people = document.querySelector('.numOfPeo').value;
    const alert1 = document.querySelector('#alert-1').innerHTML = "Please tell me amount of your bill!"
    const alert2 = document.querySelector('#alert-2').innerHTML = "Please tell me how your service was!"
    const alert3 = document.querySelector('#alert-3').innerHTML = "Please tell me how many people are sharing!"

    if (cost === "") {
        alert1
    }

    if (service === 0) {
        return alert2
    }

    if (people === "" || people <= 1) {
        return alert3
    }

    const tip = cost * service / 100;
    const total = tip / people;

    document.getElementById('totalTip').style.display = "block";
    document.getElementById('tip').innerHTML = total;
}

btn.addEventListener('click', calculateTip);

标签: javascriptalertinnerhtml

解决方案


您正在为所有内容设置innerHTML。尝试在条件范围内设置它

const cost = document.querySelector('.amount').value;
const service = document.querySelector('.service').value;
const people = document.querySelector('.numOfPeo').value;

if (cost === "") {
    document.querySelector('#alert-1').innerHTML = "Please tell me amount of your bill!"
} else if (service === 0) {
    document.querySelector('#alert-2').innerHTML = "Please tell me how your service was!"
} else if (people === "" || people <= 1) {
    document.querySelector('#alert-3').innerHTML = "Please tell me how many people are sharing!"
}

const tip = cost * service / 100;
const total = tip / people;

document.getElementById('totalTip').style.display = "block";
document.getElementById('tip').innerHTML = total;

当您编写代码时const alert1 = document.querySelector('#alert-1').innerHTML = "Please tell me amount of your bill!",您实际上正在做的事情是将属性设置alert1为. 换句话说,您的警报常量是不必要的,因为您的唯一目标是为某些情况设置 innerHTML。这些情况由您的逻辑表示。因此,将这些语句移至条件逻辑并完全删除 const 变量是有意义的。此外,为了确保一次只触发一个警报,我添加了逻辑。而且由于我们的事件监听函数的返回值无关紧要,所以没有任何理由"Please tell me amount of your bill!"innerHTML"Please tell me amount of your bill!"ifinnerHTMLif elsereturn


推荐阅读