我的类作业是创建一个网页,提示用户输入年龄,然后使用 AND 和 OR 运算符确定该用户是否太老/太小而无法参加青年运动队。
需要 2 个函数,每个函数都由自己的按钮调用。一个调用使用 AND 运算符确定资格的函数,另一个调用使用 OR 运算符的函数。
在其他作业中,我在提示用户输入并使用该输入时没有任何问题,但每次我尝试在函数中使用 if 语句时,当我单击按钮调用时,网页就像什么都没发生一样这些功能。
代码粘贴在下面:
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title>Aaron Stockdale's Age Range Page</title>
<script type="text/javascript">
function andFunction()
{
var userAge = prompt("What's your age?", " ");
if(userAge >= 16 && userAge <= 18)
document.getElementById('age').innerHTML = "Age entered " + userAge + "is in range. Can play in youth team.";}
else
document.getElementById('age').innerHTML = "Age entered " + userAge + "is not in range. Can play not in youth team.";}
}
function orFunction()
{
var userAge = prompt("What's your age?", " ");
if(userAge > 15 || userAge < 19)
document.getElementById('age').innerHTML = "Age entered " + userAge + "is in range. Can play in youth team.";}
else
document.getElementById('age').innerHTML = "Age entered " + userAge + "is not in range. Can play not in youth team.";}
}
</script>
</head>
<body>
<header>
<h1>Aaron Stockdale's Age Range Check</h1>
</header>
<section>
<br><p>This page will prompt Aaron for his age to check if he can play in the youth team.</p>
<h2>Click on the button below to enter Aaron's age</h2>
<p><input type="button" id="button1" style="border:2px solid #6A959D" value="Enter age and compare with AND operator"
onclick="andFunction()"/>
<p><input type="button" id="button1" style="border:2px solid #6A959D" value="Enter age and compare with OR operator"
onclick="orFunction()"/>
</section>
</body>
</html>
最佳答案
您在 if 和 else 语句末尾添加 },但没有添加打开它们的 {
更改为
if(userAge >= 16 && userAge <= 18) {
document.getElementById('age').innerHTML = "Age entered " + userAge + "is in range. Can play in youth team.";}
else {
document.getElementById('age').innerHTML = "Age entered " + userAge + "is not in range. Can play not in youth team.";}
关于javascript - 插入 if 语句时函数不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26566460/