在JavaScript中单击按钮不起作用时,将数字添加到递增列表中



好的,所以在我的代码中,我应该输入一个4到15之间的数字。然后我点击一个按钮添加它,一旦发生这种情况,这个数字将被添加到年龄总数和我创建的一个联赛中(它应该增加1,例如,如果我输入12,它将是1。如果我再次输入12,总数将是2(。当我尝试运行代码时,它什么也不做。

<html>
<head>
<title>Soccer Manager</title>
<script>
function addAge()
{
// gets the input age
var age = Number(document.getElementById("age").value);
// clears the input field
document.getElementById("age").value = "";
// checks if age is between 4 and 15
if(age >= 4 && age <= 15){
// table cell to display total number of children
var total = document.getElementById("total");
// table cell to display total number of junior
var junior = document.getElementById("junior");
// table cell to display total number of intermediate
var intermediate = document.getElementById("intermediate");
// table cell to display total number of senior
var senior = document.getElementById("senior");
// increase total number of children by 1
total.innerHTML = Number(total.innerHTML) + 1;
// if its a junior age
if(age<=7)
// increase total number of junior by 1
junior.innerHTML = Number(junior.innerHTML) + 1;

// if its a intermediate age
else if(age<=11)
// increase total number of intermediate by 1
intermediate.innerHTML = Number(intermediate.innerHTML) + 1;

// else it will be a senior age
else
// increase total number of senior by 1
senior.innerHTML = Number(senior.innerHTML) + 1;
}
// if age is not between 4 and 15 alert an error
else{
window.alert("Age should be between 4 and 15");
}
}
}
</script>
</head>
<body>
<center>
<h1>
Soccer Manager
</h1>
<div>
<table>
<tr>
<th>Total Children</th>
<td id="total">0</td>
</tr>
<tr>
<th>Junior</th>
<td id="junior">0</td>
</tr>
<tr>
<th>Intermediate</th>
<td id="intermediate">0</td>
</tr>
<tr>
<th>Senior</th>
<td id="senior">0</td>
</tr>
</table>

<input type="number" placeholder="Age"  id="age">
<button onClick="addAge()">Add</button>
</div>
</center>
</body>

</html>

您似乎忘记在语句中添加大括号(}(。


要修复它,您需要在以下位置添加大括号。

if (age >= 4 && age <= 15) {
// Code...
} // Add me!
if (age <= 7) { // Add here!
// Code...
} // Add here!
else if (age <= 11) { // Add here!
// Code...
} // Add here!

请记住添加大括号以使您的JavaScript代码正常工作!

最新更新