javascript - 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);
解决方案
您正在为所有内容设置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!"
if
innerHTML
if else
return
推荐阅读
- firebase - LateInitializationError: 字段 '_imagePicked@20490806' 尚未初始化
- javascript - 如何定义具有默认值的组件
- templates - Netsuite 打印模板:无法访问实体字段
- reactjs - 使用 localStorage 在 React JS 中存储当前登录的用户数据
- c# - 使用 CSV 助手进行错误映射,一个字段的值为空
- node.js - 将标头发送给客户端后无法设置标头
- html - 字体真棒图标未显示在选择框中
- google-cloud-platform - Google Cloud Platform OAuth 应用程序验证问题
- wpf - (VB.NET) 对象引用未设置为对象的实例。无法解决问题
- ocaml - 如何在 OCaml 中结合函数的布尔和单位输出?