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函數?
您正在將DOM元素數組與字符串進行比較,因此您的函數將不會執行任何操作。除此之外,如果將整個腳本放入onload事件處理程序並通過JS本身將事件偵聽器附加到按鈕,將會有所幫助。這只是確保函數在附加到DOM對象之前被初始化的最佳實踐。 – Shashank 2015-03-31 17:55:56