如何通过获取用户输入和使用按钮来运行JavaScript函数
How can I run a JavaScript function by taking user input & using a button?
<!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
只是为了确保您知道,这不是最佳实践、效率或最佳方法。 这只是一个简单的示例,可帮助您稍微了解该过程,以帮助您获得语言的基础。
相关文章:
- 将文本框链接到由按钮运行的javascript公式
- 从页面javascript按钮运行Node.JS
- 在同一页面上单击按钮运行不同的代码
- 如何阻止一个Submit按钮运行Submit Click功能
- 根据选中的按钮运行不同的计算时,设置单选按钮
- 单击javascript中的按钮运行python脚本
- 链接按钮运行的代码无效
- 从按钮运行函数
- 为什么获胜't我的HTML按钮运行我的JavaScript函数
- 使用html按钮运行python脚本
- 点击一个按钮运行一个功能-不工作
- 点击按钮运行Javascript
- Chrome扩展赢得't点击按钮运行功能
- 如何使图像按钮运行PHP脚本
- 单击按钮运行函数并添加Class
- 点击浏览器返回按钮运行动画
- 如何从HTML中的一个按钮运行整个Javascript页面?
- 选择按钮运行功能
- 点击html按钮运行PHP函数
- 如何使一个按钮运行php代码与ajax,无需刷新页面购物车