javascript - 为什么我的小费计算器中不断得到 NaN 值?
问题描述
我无法找出我的代码出了什么问题。谢谢你。我已通过 codepen 附加到代码的链接。
https://codepen.io/tenzin12/pen/rNmmPbv
`const confirmBtn = document.querySelector(".confirm");
const tipField = document.querySelector(".p1");
const totalField = document.querySelector(".p2");
const tipPercentage = document.querySelector("#tip").children;
const customTip = document.querySelector(".custom").value;
const inputAmt = document.querySelector("#amount").value;
const totalPerson = document.querySelector(".number_of_people").value;
const calcFunction = (bill, percent, diners) => {
const percentage = percent / 100;
const tipPerPerson = (bill * percentage) / diners;
const finalBillPerPerson = bill / diners;
const finalWithTip = finalBillPerPerson + tipPerPerson;
tipField.textContent = tipPerPerson;
totalField.textContent = finalWithTip;
};
for (let i = 0; i < tipPercentage.length; i++) {
tipPercentage[i].addEventListener("click", () => {
if (parseInt(totalPerson) > 0) {
if (tipPercentage[i].value.toUpperCase() === "CUSTOM") {
calcFunction(parseFloat(inputAmt), parseInt(customTip), parseInt(totalPerson));
}
}
calcFunction(parseFloat(inputAmt), parseInt(tipPercentage[i].value), parseInt(totalPerson));
});
}
`
解决方案
当您需要对元素值进行计算时,您需要在计算时收集这些值。您预先收集它们 - 但是当您计算函数时,它使用的是那些旧值。我将它们移到了您的功能中。请注意我是如何摆脱大多数parseInt
and函数来支持做同样事情parseFloat
的最小运算符的。+
此外,我稍微简化了代码并进行了验证,以防止总计运行在 0 人或 0 数量上。最后,我将您的for
循环更改为 HTMLCollectionforEach
循环。我发现它更容易阅读和维护
const confirmBtn = document.querySelector(".confirm");
const tipField = document.querySelector(".p1");
const totalField = document.querySelector(".p2");
const tipPercButtons = document.querySelectorAll("#tip input.percentage");
const calcFunction = (bill, percent, diners) => {
const percentage = percent / 100;
const tipPerPerson = (bill * percentage) / diners;
const finalBillPerPerson = bill / diners;
const finalWithTip = finalBillPerPerson + tipPerPerson;
tipField.textContent = tipPerPerson;
totalField.textContent = finalWithTip;
};
tipPercButtons.forEach((el) =>
el.addEventListener("click", (e) => {
const customTip = +document.querySelector(".custom").value;
const inputAmt = +document.querySelector("#amount").value;
const totalPerson = +document.querySelector(".number_of_people").value;
if (isNaN(totalPerson) || isNaN(inputAmt)) {
alert("Please designate the number of people and the amount of the bill")
return;
}
if (totalPerson === 0) return;
let val
if (e.target.value.toUpperCase() === "CUSTOM") val = customTip;
else val = parseInt(e.target.value);
calcFunction(inputAmt, val, totalPerson);
})
);
推荐阅读
- php - 如何检索 Kaltura 中超过 10k 标记的所有媒体条目?
- java - 插入模型 android studio 时出错
- git - 如何根据 master 上的新更改继续我的更改
- c# - DataGrid 在其 ItemSource 更新时不创建行,有时重复条目
- merge - 如何确定merge()后是否需要git_commit_create()?
- hybris - 如何将 powertools 项目移动到我的商店
- ios - iOS如何快速将NSArray中的字典数组添加到现有的NSMutableArray?
- php - 匹配括号之间的内容并获取 url 并使用 RegExp PHP 将其更改为 img 标签
- c# - C# 实体框架。根据“名称”列对所有分层节点进行排序
- schema.org - 对于与特定地点相关的商品价格表,我应该使用哪种类型的 schema.org?