因此,我正在尝试在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);发布于 2020-04-09 00:49:35
您正在为所有内容设置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设置为"Please tell me amount of your bill!",并将innerHTML属性也设置为"Please tell me amount of your bill!"。换句话说,您的警报常量是不必要的,因为您的唯一目标是为某些情况设置innerHTML。这些情况由您的if逻辑表示。因此,将这些innerHTML语句移到条件逻辑中并完全删除常量变量是有意义的。此外,为了确保一次只触发一个警报,我添加了if else逻辑。由于我们的事件侦听器函数的返回值无关紧要,因此没有理由return任何东西
https://stackoverflow.com/questions/61105644
复制相似问题