用户在变量中的输入

问题描述 投票:-3回答:3

我试图在变量中保存用户答案,然后在if语句中使用该变量。我尝试了以下代码,但它不起作用:

<input type="number" id="x"/>
<button onclick="calc();";>try</button>
<script>
  function calc() {
      var age = document.GetElementById("x").value;

      if (age >= 35) {
        alert("you are old enough");
      } else {
        alert("you are too young");
      }
  }
</script>
javascript html
3个回答
-1
投票

你有一个小错字:“getElementById”的第一个字符应该是小写。

您可以通过打开开发人员的控制台并查看消息来查看此类错误:

test.html:6 Uncaught TypeError: document.GetElementById is not a function
    at calc (test.html:6)
    at HTMLButtonElement.onclick (test.html:2)

-1
投票

你的尝试几乎是正确的,但GetElementById不是一个函数,它必须是getElementById而不是。

我还删除了HTML中的两个不必要的分号,这里不需要它们。

 function calc() {
      var age = document.getElementById("x").value;

      if (age >= 35) {
        alert("you are old enough");
      } else {
        alert("you are too young");
      }
  }
<input type="number" id="x"/>
<button onclick="calc()">try</button>

-1
投票

你的getElementById不应该是大写的。

  <input type="number" id="x"/>
 <button onclick="calc();">try</button>
 <script>
 function calc() {
     //Here is your mistake
     var age = document.getElementById("x").value;

  if (age >= 35) {
    alert("you are old enough");
   } else {
    alert("you are too young");
   }
   }
 </script>
© www.soinside.com 2019 - 2024. All rights reserved.