如何通过获取用户输入和使用按钮来运行JavaScript函数

How can I run a JavaScript function by taking user input & using a button?

本文关键字:按钮 运行 JavaScript 函数 获取 何通过 用户 输入      更新时间:2023-09-26
<!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>

这段代码有什么问题?每当我按下按钮时,什么都没有发生!!我一次又一次地尝试,但由于某种原因,它找不到用户输入并输出任何警报值!请帮忙!

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

这应该会给你正确的结果,该结果将适用于你的 if

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