<!doctype html>
<html>
<head>
<title> Daily Recommended Exercise </title>
</head>
<body>
<h2>Your Daily Exercise Schedule</h2>
<p>Please select your age group:</p>
<form>
0 - 5: <input type = "radio" name = "PickAge" value = "Age1">
<br/>
6 - 17: <input type = "radio" name = "PickAge" value = "Age2">
<br/>
18 - 64: <input type = "radio" name = "PickAge" value = "Age3">
<br/>
65 - 150: <input type = "radio" name = "PickAge" value = "Age4">
<br/>
<input type="button" onclick = "exerciseRecommend();" value = "Enter"></input>
</form>
<script type = "text/javascript">
function exerciseRecommend()
{
var age = document.getElementsByName("PickAge");
if (age=="Age1")
{
alert("Physical activity in infants and young children is necessary for healthy growth and development. There are no guidelines for children at this age though regular physical activity is recommended.");
}
else if (age=="Age2")
{
alert("At this age you should do 60 minutes or more of physical activity each day. This includes, aerobic endurance and strength exercises.");
}
else if (age=="Age3")
{
alert("At this age you should be doing two hours and thirty minutes or more of moderate aerobic endurance and strength exercises activity every week OR one hour fifteen minutes of intense aerobic endurance and strength exercises activity OR a mix of the two.");
}
else if (age=="Age4")
{
alert("At this age you should be exercising 2-3 hours a week. It is recommended that you should be doing mild endurance and strength activities.");
}
}
</script>
</body>
</html>
这段代码有什么问题?每当我按下按钮都没有任何反应!!我一次又一次地尝试但由于某种原因它没有找到用户输入并输出任何警报值!请帮忙!
答案 0 :(得分:0)
所以,让我们来看看你的age
变量。如果您在定义它之后console.log(age)
,它将返回名称为&#34; PickAge&#34;的所有元素的节点列表。你想要的是具体的那一个,即经过检查的那个。
// Get a list of all the select-able ages
var allAges = document.getElementsByName("PickAge");
// Define a variable that will hold our selected age
var age;
// Iterate through all of the select-able ages
for (i = 0; i < allAges.length; i++) {
// If the selected age is checked, set it to the "age" variable
if (allAges[i].checked === true) {
// We grab only the value here because that's what you check later
age = allAges[i].value;
}
}
这应该会给你正确的结果,这将与你的if&lt;警报。你可能想在最后添加一个else语句,以防用户没有选择任何年龄。
只是为了确保您知道,这不是最佳实践,效率或最佳方式。这只是一个简单的例子,可帮助您了解该过程,以帮助您获得该语言的基础。