用户在变量中的输入

时间:2018-04-23 18:14:33

标签: javascript html

我正在尝试将用户答案保存在变量中,然后在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>

3 个答案:

答案 0 :(得分:-1)

你有一个小错字:第一个字符&#34; getElementById&#34;应该是小写。

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

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

答案 1 :(得分:-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>

答案 2 :(得分:-1)

您的尝试几乎是正确的,但GetElementById不是函数,而是getElementById

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

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

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