首页 > 解决方案 > 为什么我的小费计算器中不断得到 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));
  });
}
`

标签: javascripthtmlcss

解决方案


当您需要对元素值进行计算时,您需要在计算时收集这些值。您预先收集它们 - 但是当您计算函数时,它使用的是那些旧值。我将它们移到了您的功能中。请注意我是如何摆脱大多数parseIntand函数来支持做同样事情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);
    })
);

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


推荐阅读