我试图在变量中保存用户答案,然后在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”的第一个字符应该是小写。
您可以通过打开开发人员的控制台并查看消息来查看此类错误:
test.html:6 Uncaught TypeError: document.GetElementById is not a function
at calc (test.html:6)
at HTMLButtonElement.onclick (test.html: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>
你的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>