Javascript 无法访问document.getElementById为的输入字段中的值
我无法使用document.getElementById访问输入字段中的值,以检查输入数字是偶数还是奇数 你能告诉我我的密码有什么问题吗 提前谢谢你Javascript 无法访问document.getElementById为的输入字段中的值,javascript,html,Javascript,Html,我无法使用document.getElementById访问输入字段中的值,以检查输入数字是偶数还是奇数 你能告诉我我的密码有什么问题吗 提前谢谢你 <!DOCTYPE html> <html> <head> <title>Even or odd</title> <meta charset="utf-8"/> <link h
<!DOCTYPE html>
<html>
<head>
<title>Even or odd</title>
<meta charset="utf-8"/>
<link href="style.css" rel="stylesheet"/>
</head>
<body>
<form>
<p>Please type a number in the field and press the button to check if this is an even or an odd number.</p>
<input type="text" id="num" placeholder="Enter a number"/>
<button type="button" onclick="myFunction()">Click Me!</button>
</form>
<script>
var a = parseInt(document.getElementById("num").value);
function myFunction(){ if ((a/2)==%){
alert("The number is odd");
} else {
alert("The number is even");
}
}
</script>
</body>
</html>
您需要移动在函数中获取值的代码行。实际上,当页面加载时,它只运行一次
function myFunction(){
var a = parseInt(document.getElementById("num").value);
另外,我不知道a/2==%应该是什么意思,但这是一个语法错误
if (a % 2 != 0) // odd test
if (a % 2 == 0) // even test