根据输入值计算最大值、最小值和平均值 [英] Calculate maximum, minimum and average from input values
问题描述
我正在尝试创建 6 个由 制成的文本框,前 3 个作为输入,后 3 个作为输出.三个输入文本框读取 3 个数字.单击计算按钮时,应计算出 3 个输入数字的最大值、最小值和平均值,并显示在带有相应标签的文本框中.我的代码不起作用有什么原因吗?
I'm trying to create 6 textboxes made from , top 3 serve as input, bottom 3 serve as the output. Three input textboxes read 3 numbers. When the Calculate button is clicked, the maximum, minimum, and average of 3 input numbers should be calculated and displayed in the textbox with corresponding label. Is there a reason why my code doesn't work?
function maximum() //find the max
{
var max;
if (document.getElementsByTagName("input")[0].value > document.getElementsByTagName("input")[1].value && document.getElementsByTagName("input")[0].value > document.getElementsByTagName("input")[2].value) {
max = document.getElementsByTagName("input")[0].value;
} else if (document.getElementsByTagName("input")[1].value > document.getElementsByTagName("input")[0].value && document.getElementsByTagName("input")[1].value > document.getElementsByTagName("input")[2].value) {
max = document.getElementsByTagName("input")[1].value;
} else {
max = document.getElementsByTagName("input")[2].value;
}
document.getElementsByTagName("output")[0] = max;
//alert(maximumDemo.innerHTML);
}
function average() //find the average
{
var total = 3;
var i, aver;
aver = (document.getElementsByTagName("input")[0].value + (document.getElementsByTagName("input")[1].value + (document.getElementsByTagName("input")[2].value))) / total;
document.getElementsByTagName("output")[1] = aver;
}
function minimum() {
if (document.getElementsByTagName("input")[0].value < document.getElementsByTagName("input")[1].value && document.getElementsByTagName("input")[0].value < document.getElementsByTagName("input")[2].value) {
min = document.getElementsByTagName("input")[0].value;
} else if (document.getElementsByTagName("input")[1].value < document.getElementsByTagName("input")[0].value && document.getElementsByTagName("input")[1].value < document.getElementsByTagName("input")[2].value) {
min = document.getElementsByTagName("input")[1].value;
} else {
min = document.getElementsByTagName("input")[2].value;
}
document.getElementsByTagName("output")[2] = min; //find the minimum
//alert(minimumDemo.innerHTML);
}
<form>
Number 1: <input type="text" name="num1"> <br> Number 2: <input type="text" name="num2"> <br> Number 3: <input type="text" name="num3"> <br> Maximum: <output type="text" name="max"></output> <br>
<!--preferably in textbox form-->
Average: <output type="text" name="avg"></output> <br>
<!--preferably in textbox form-->
Minimum: <output type="text" name="min"></output> <br>
<!--preferably in textbox form-->
<br><br>
</form>
<button onCLick="maximum();average();minimum();">Calculate</button>
推荐答案
您有几个问题,但最大的是您试图将 output
元素本身设置为你的数学问题而不是设置.textContent
你的元素的代码到你的数学答案.
You have several problems, but the biggest was that you were attempting to set your output
elements themselves to the answers to your math problems instead of setting the .textContent
of your elements to the answers to your math.
现在,既然您刚刚学习了所有这些,让我们在它们变得一成不变之前改掉一些坏习惯.毫无疑问,您已经从其他人使用的代码中复制了大部分代码,不幸的是,网络上的大多数代码都是以这种方式创建的,而不是由真正了解他们所写内容的人创建的.
Now, since you are just learning all of this, let's break some bad habits before they become set in stone. No doubt you've copied much of your code from what you've seen others use and, unfortunately, most of the code on the web gets created this way and not by people who really understand what they are writing.
考虑到这一点...
不要通过 HTML 事件属性设置事件处理程序(即 onclick
、onmouseover
等).这是一项已有 25 年历史的技术,我们在拥有现代标准和最佳实践之前就使用了它,而且由于它易于使用,人们一直在使用它.但是有多种原因导致您不应使用这种技术,而应将 JavaScript 与 HTML 分开.相反,将您的 JavaScript 分开并使用 .addEventListener()
将您的元素连接到它们各自的回调函数.
Do not set up event handlers via HTML event attributes (i.e. onclick
, onmouseover
, etc.). This is a 25+ year old technique that we used before we had modern standards and best practices and because it's easy to use, people keep using it. But there are a variety of reasons why you should not use this technique and instead separate your JavaScript from your HTML. Instead, keep your JavaScript separate and use .addEventListener()
to hook up your elements to their respective callback functions.
只需获取一次元素引用,而不是每次运行函数时,因为扫描文档中的元素需要时间和资源.没有理由一遍又一遍地扫描相同的元素.
Just get your element references once, not every time you run your functions because scanning the document for an element takes time and resources. There's no reason to keep scanning for the same element over and over.
与此有关.小心.getElementsByTagName()
因为它返回一个活动节点列表",这意味着它必须重新扫描文档以确保它的列表保持最新.这在性能方面可能非常浪费.相反,.getElementById()
、.querySelector()
和 .querySelectorAll()
应该是扫描单个元素或元素组的最常用方法.
Related to that. Be careful with .getElementsByTagName()
as it returns a "live node list", which means that it has to re-scan the document to ensure that it keeps its list up to date. This can be extremely wasteful in terms of performance. Instead, .getElementById()
, .querySelector()
and .querySelectorAll()
should probably be the most common ways to scan for individual elements or groups of elements.
output
元素没有 HTML type
属性.input
和 button
元素允许设置 type
.输出
纯粹是一个语义元素,就所有意图和目的而言,在功能上与 span
元素没有太大区别.这只是让浏览器知道它将包含页面设计者认为是来自任何地方的某种输出的内容的一种方式.任何桌面版本的 IE 也不支持它(如果这对您很重要).你使用它很好,但我认为你误解了它是什么以及它是如何使用的.
The output
element doesn't have an HTML type
attribute. input
and button
elements allow for setting the type
. output
is purely a semantic element, and for all intents and purposes, not that much functionally different from a span
element. It's just a way for the browser to know that it will contain something that the page designer deems as some kind of output, from anywhere. It's also not supported in any desktop version of IE (if that matters to you). It's fine that you are using it, but I think you misunderstand what it's for an how it's used.
您的解决方案中确实不需要任何 if/then
代码,因为 JavaScript 具有内置的 Math
对象,它具有 .max
和 .min
方法完全符合您的要求.
You really don't need any if/then
code in your solution because JavaScript has a built-in Math
object, which has .max
and .min
methods that do exactly what you are attempting.
请记住,HTML 中的T"代表文本".无论您认为您在表单字段中输入什么,它都会作为文本处理,当 JavaScript 获取该值时,它也会将其作为文本进行处理.而且,在 JavaScript 中,+
运算符可以表示字符串连接,也可以表示数学加法.它执行哪一个取决于操作数是什么.如果操作数之一是字符串,则完成字符串连接.因此,在对它们进行任何数学运算之前,您需要将 input
元素中的数据转换为数字.这可以通过多种方式(隐式和显式)完成,但一种简单的方法是在可转换为数字的字符串前添加 +
运算符,您将在下面是我的平均代码.
Remember that the "T" in HTML stands for "Text". No matter what you think you are entering into a form field, it is processed as text and when JavaScript obtains that value, it processes it as text as well. And, in JavaScript the +
operator can mean string concatenation or it can mean mathematical addition. Which one it does depends on what the operands are. If one of the operands is a string then string concatenation is done. So, you need to convert the data in your input
elements to numbers before you do any math on them. This can be done in a variety of ways (implicit and explicit), but one simple way is to prepend a +
operator in front of a string that is convertible to a number and you'll see that in my average code below.
最后(这不会导致您的代码无法工作,但您应该知道),每个 HTML 文档都必须在 < 之前有一个
和 <head>
部分.body> 部分中必须有一个非空的
元素,文档才能被认为是有效的.浏览器不验证 HTML,它们只是跳过它们不理解的 HTML.这意味着您很可能在浏览器中拥有一个对您有效"的网页,但在技术上是不正确的.始终在 http://validator.w3.org 验证您的 HTML 以确保它是正确的.
Lastly (and this wasn't causing your code to not work, but you should know), every HTML document must have a <head>
section just prior to the <body>
and the <head>
section must have a non-empty <title>
element within it for the document to be considered valid. Browsers don't validate HTML, they simply skip HTML that they don't understand. This means that you could very well have a web page that "works" for you in your browser, but is technically incorrect. Always validate your HTML at http://validator.w3.org to ensure it's correct.
<!doctype html>
<html>
<head>
<title>Basic JavaScript 101</title>
</head>
<body>
<form>
Number 1: <input type="text" name="num1"> <br>
Number 2: <input type="text" name="num2"> <br>
Number 3: <input type="text" name="num3"> <br>
Maximum: <output id="max"></output> <br> <!-- output should not be in input type elements -->
Average: <output id="avg"></output> <br> <!-- output should not be in input type elements -->
Minimum: <output id="min"></output> <br> <!-- output should not be in input type elements -->
<br><br>
</form>
<button type="button" id="calc">Calculate</button>
<script>
// Get references to the elements just once
var num1 = document.querySelector("[name='num1']");
var num2 = document.querySelector("[name='num2']");
var num3 = document.querySelector("[name='num3']");
var max = document.getElementById("max");
var avg = document.getElementById("avg");
var min = document.getElementById("min");
var btn = document.getElementById("calc");
// Set up your event handler(s) in JavaScript, not with HTML attributes
btn.addEventListener("click", function(){
maximum();
average();
minimum();
});
function maximum() {
// You can't just set an element to a value. You have to set the content of the
// element to a value. Also, JavaScript provides a built-in Math object that
// can get you the maximum number from a set of numbers. No if/then needed.
max.textContent = Math.max(num1.value, num2.value, num3.value);
}
function average() {
// Convert values to numbers and do math
avg.textContent = (+num1.value + +num1.value + +num3.value) / 3
}
function minimum() {
// You can't just set an element to a value. You have to set the content of the
// element to a value. Math can also get you the minimum number in a set:
min.textContent = Math.min(num1.value, num2.value, num3.value);
}
</script>
</body>
</html>
这篇关于根据输入值计算最大值、最小值和平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!