为什么我的表格输出nan



所以我有此表格正在执行非常基本的计算,当我提交时,它会导致NAN。

让我感到困惑的事情是,当我执行分配给每个输入值的变量之一的类型时,它返回"数字",但结果我得到了NAN。谁能告诉我为什么我做错了什么?

这是我的html:

<form name="baddiesCost">
     <input type="number" placeholder="Total Caught" name="goomba" id="goomba-form">
     <input type="number" placeholder="Total Caught" name="bobombs" id="bob-ombs-form">
     <input type="number" placeholder="Total Caught" name="cheepCheeps" id="cheep-form">
     <button id="submitForm">Submit</button>
</form>
 <h1 id="total"></h1>

这是我的JavaScript:

document.baddiesCost.addEventListener("submit", function(e) {
  e.preventDefault();
  var goombaCaught = document.baddiesCost.goomba.value * goombaCost;
  var bobombsCaught = document.baddiesCost.bobombs.value * bobombsCost;
  var cheepsCaught = document.baddiesCost.cheepCheeps.value * cheepCost;
  var goombaCost = 5;
  var bobombsCost = 7;
  var cheepCost = 11;
  var showTotal = document.getElementById("total");
  var total = goombaCaught + bobombsCaught + cheepsCaught;
  showTotal.textContent = cheepsCaught;
  console.log(bobombsCaught);
  console.log(typeof bobombsCaught);
})

此语句document.baddiesCost.bobombs.value * bobombsCost;使用此时尚未定义的变量bobombsCost

所以,它类似于:document.baddiesCost.bobombs.value * undefined;,它将为NaN

在使用之前,在使用之前求解此put变量不重新化:

document.baddiesCost.addEventListener("submit", function(e) {
      e.preventDefault();
      var goombaCost = 5;
      var bobombsCost = 7;
      var cheepCost = 11;
      var goombaCaught = document.baddiesCost.goomba.value * goombaCost;
      var bobombsCaught = document.baddiesCost.bobombs.value * bobombsCost;
      var cheepsCaught = document.baddiesCost.cheepCheeps.value * cheepCost;
      var showTotal = document.getElementById("total");
      var total = goombaCaught + bobombsCaught + cheepsCaught;
      showTotal.textContent = cheepsCaught;
      console.log(bobombsCaught);
      console.log(typeof bobombsCaught);
    })

无论如何,NaN是数字类型,您可以参考以下帖子以获取更多解释。

相关内容

  • 没有找到相关文章

最新更新