rfo*_*er2 2 html javascript numbers average
我对这个基本问题表示歉意,但我长期以来一直在努力使这项工作正常进行,但我似乎无法让这段代码返回一个值。
我很尴尬地承认我已经尝试让它工作多久了,以及我看过多少相关的 StackOverflow 问题,但是,没有一个像我的代码那么简单,当我试图做出更接近于如何我的看起来,它只是不会发出任何警报。
这个想法如下:
无论我进行了多少次迭代,我的警报都是 NaN。我真的需要一些建议。提前致谢!
<html>
<head>
<title> Javascript </title>
<body>
<p> Enter two number for an average below </p>
<p> Number 1<input type="text" id="userInput1"></input></p>
<p> Number 2<input type="text" id="userInput2"></input></p>
<button id="averageButton"> Calculate</button>
<script type="text/javascript">
function average(a, b) {
return ((a + b) /2);
}
document.getElementById("averageButton").onclick = function (){
var a = document.getElementById("userInput1").value;
var b = document.getElementById("userInput2").value;
alert(average());
}
</script>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
您未能将数字 a,b 传递给您的函数 - 一个简单的错误。
但由于输入被视为字符串,因此您还需要将它们转换为数字 a*1
查看注释代码
<html>
<head>
<title> Javascript </title>
<body>
<p> Enter two number for an average below </p>
<p> Number 1<input type="text" id="userInput1"></input></p>
<p> Number 2<input type="text" id="userInput2"></input></p>
<button id="averageButton"> Calculate</button>
<script type="text/javascript">
function average(a, b) {
// force the input as numbers *1
return ((a*1 + b*1) /2);
}
document.getElementById("averageButton").onclick = function (){
var a = document.getElementById("userInput1").value;
var b = document.getElementById("userInput2").value;
// pass the numbers to the average function!
alert(average(a,b));
}
</script>
</body>
</html>Run Code Online (Sandbox Code Playgroud)