gpt4 book ai didi

javascript - 使用 onchange 事件处理程序计算平均值

转载 作者:行者123 更新时间:2023-11-30 20:59:01 24 4
gpt4 key购买 nike

我需要使用 onchange 事件处理程序计算 5 个数字的平均值。我是编码新手,并不完全了解 onchange 的工作原理。我也对如何在“结果”框中显示我的 calcAvg 函数的返回 # 感到困惑

<! doctype html >

<html lang = "en">
<head>
<title> Calculate Average </title>
</head>

<body>
Number 1:<input type="number" id="number 1" Value="0"
onchange="calcAvg()"> </br> //do I put anything in between the ()of
onchange?
Number 2:<input type="number" id="number 2" Value="0"
onchange="calcAvg()"> </br>
Number 3:<input type="number" id="number 3" Value="0"
onchange="calcAvg()"> </br>
Number 4:<input type="number" id="number 4" Value="0"
onchange="calcAvg()"> </br>
Number 5:<input type="number" id="number 5" Value="0"
onchange="calcAvg()"> </br>
Result :<input type=" number" id="result"> </br>
<input type= 'button' value='calculate' id= 'calculate'>
<div id= "result"> </div>//

<script>
function calcAvg ( number 1, number 2 ,number 3, number 4, number 5)
{
return ((number 1 + number 2 +number 3+ number 4+ number 5)/5)
}
</script>




</body>
</html>

最佳答案

<html lang = "en">
<head>
<title> Calculate Average </title>
</head>

<body>
Number 1:<input type="number" id="number1" Value="0"
onchange="calcAvg()"> </br>
Number 2:<input type="number" id="number2" Value="0"
onchange="calcAvg()"> </br>
Number 3:<input type="number" id="number3" Value="0"
onchange="calcAvg()"> </br>
Number 4:<input type="number" id="number4" Value="0"
onchange="calcAvg()"> </br>
Number 5:<input type="number" id="number5" Value="0"
onchange="calcAvg()"> </br>
Result :<input type=" number" id="result"> </br>
<input type= 'button' onClick="calcAvg()" id= 'calculate'>
<div id="result"> </div>//


<script>
function calcAvg () {
var num1 = document.getElementById("number1").val() || 0;
var num2 = document.getElementById("number2").val() || 0;
var num3 = document.getElementById("number3").val() || 0;
var num4 = document.getElementById("number4").val() || 0;
var num5 = document.getElementById("number5").val() || 0;

document.getElementById("result").value=((num1 + num2 +num3+ num4+
num5)/5);
}
</script>

通过 ID 从输入中获取值,然后对这些值进行平均。从 on change 属性调用函数。您可以从按钮的 onclick 调用相同的函数。通过获取结果 ID 并为其添加值来设置值。

关于javascript - 使用 onchange 事件处理程序计算平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47315174/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com