求助:将用户输入存入变量并用于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 isdocument.getElementById("x")(note the lowercaseg). That's why your code can't locate the input element in the first place. - Input values are strings by default. The
valueproperty 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 totruebecause of character ASCII values). You need to convert the value to a number first usingparseInt()orNumber().
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
相关产品推荐
相关产品推荐

