You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:将用户输入存入变量并用于if语句的代码无法运行

Fixing Your Age Checker Code

Hey there! Let's get your code working properly—there are two key issues tripping it up right now:

  • JavaScript is case-sensitive! You used document.GetElementById("x"), but the correct method name is document.getElementById("x") (note the lowercase g). That's why your code can't locate the input element in the first place.
  • Input values are strings by default. The value property of a number input returns a string, not a numeric value. If you compare a string directly to a number (like "30" >= 35), JavaScript will do unexpected string-based comparisons (e.g., "4" >= "35" would incorrectly evaluate to true because of character ASCII values). You need to convert the value to a number first using parseInt() or Number().

Here's the corrected code that addresses both issues:

<input type="number" id="x"/> 
<button onclick="calc();">try</button> 
<script> 
function calc() { 
  // Fix the method name and convert value to a number
  var age = parseInt(document.getElementById("x").value); 
  if (age >= 35) { 
    alert("you are old enough"); 
  } else { 
    alert("you are too young"); 
  } 
} 
</script>

Alternatively, you could use Number(document.getElementById("x").value) instead of parseInt()—both work well for converting the input string to a number here.

内容的提问来源于stack exchange,提问作者Ali Jafari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:08:25