2015-03-31 56 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語句。

只是爲了確保您知道,這不是最佳實踐,高效或最佳做法。這只是一個簡單的例子,可以幫助您瞭解該過程,幫助您獲得語言的基礎。

相關問題