【问题标题】:user input in a variable变量中的用户输入
【发布时间】:2018-04-23 18:14:32
【问题描述】:

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

【问题讨论】:

  • GetElementById --> getElementById.
  • GetElementById 不存在。检查你的拼写。使用browser console (dev tools)(点击F12)并阅读任何错误。
  • 第二个半列在:&lt;button onclick="calc();";&gt; 更改为:&lt;button onclick="calc();"&gt;
  • 在我的答案中添加了一个 sn-p。如果这对您有用,请接受:D。

标签: javascript html


【解决方案1】:

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

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

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

【讨论】:

  • 我能否得到关于为什么这个答案被否决的提示?
【解决方案2】:

您的尝试几乎是正确的,但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>

【讨论】:

    【解决方案3】:

    您的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>
    

    【讨论】:

      猜你喜欢
      • 2012-11-18
      • 1970-01-01
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 2018-11-26
      • 2018-12-29
      • 1970-01-01
      相关资源
      最近更新 更多