2015-03-31 52 views
0
<!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> 

这段代码有什么问题?每当我按下按钮什么都没有发生!我一次又一次尝试,但由于某种原因,它没有找到用户输入并输出任何警报值!请帮忙!如何通过用户输入和使用按钮来运行JavaScript函数?

+3

您正在将DOM元素数组与字符串进行比较,因此您的函数将不会执行任何操作。除此之外,如果将整个脚本放入onload事件处理程序并通过JS本身将事件侦听器附加到按钮,将会有所帮助。这只是确保函数在附加到DOM对象之前被初始化的最佳实践。 – Shashank 2015-03-31 17:55:56

回答

0

Shashank最好的做法是通过JS本身附加事件监听器,但在你的情况下,我会假设你正在学习这门语言,只是想知道它是什么以及它是如何工作的。

因此,让我们来看看您的age变量。如果您在定义它之后console.log(age),它将返回名为“PickAge”的所有元素的节点列表。你想要的是一个特定的那个,被选中的那个。

// 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; 
    } 
} 

这应该给你正确的结果,将与您如果<警戒工作。不过,如果用户没有选择任何年龄,您可能希望在最后添加一个else语句。

只是为了确保您知道,这不是最佳实践,高效或最佳做法。这只是一个简单的例子,可以帮助您了解该过程,帮助您获得语言的基础。

相关问题