为什么我一直在小费计算器中获取NaN值



我找不到代码中出了什么问题。非常感谢。我已通过代码笔将链接附加到代码。

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));
});
}
`

当需要对元素值进行计算时,需要在计算时收集这些值。你事先收集了它们,但当你计算函数时,它使用了那些旧值。我把这些移到你的功能中了。请注意,我是如何去掉大多数parseIntparseFloat函数,转而使用做同样事情的最小+运算符的。

此外,我稍微简化了代码,并进行了验证,以防止在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);
})
);

更新的笔:https://codepen.io/john-tyner/pen/MWmmLMQ?editors=1111

我分析了您的代码,在获取代码中的输入值时出现了一些错误。下面是正确的代码。希望这能奏效在代码中进行以下小更改:

const inputAmt = document.querySelector("#amount");
const totalPerson = document.querySelector(".number_of_people");

这个在if块外部的底部

calcFunction(
parseFloat(inputAmt.value),
parseInt(tipPercentage[i].value),
parseInt(totalPerson.value)
);

总的来说,你的计算器很有趣。

最新更新