我无法将一切都集中在一起。 这就是我得到的:
xxx xxx xxx xxx xxx
我想要的是
xxx
xxx
xxx
xxx
xxx
在网页中以眼睛为中心
我也无法获得平均功能。我不知道我哪里出错了。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Average Calculator</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<h1 style="text-align:center;">My Average Calculator</h1>
<script type="text/javascript">
function getTotal() {
var form = document.getElementById('number');
var numb1 = parseInt(form.numb1.value);
var numb2 = parseInt(form.numb2.value);
var numb3 = parseInt(form.numb3.value);
var numb4 = parseInt(form.numb4.value);
var numb5 = parseInt(form.numb5.value);
var total = document.getElementById('total');
var average = document.getElementById('average');
if (!numb1) {
numb1 = 0;
}
if (!numb2) {
numb2 = 0;
}
if (!numb3) {
numb3 = 0;
}
if (!numb4) {
numb4 = 0;
}
if (!numb5) {
numb5 = 0;
}
total.innerHTML = 'Total: ' + (numb1 + numb2 + numb3 + numb4 + numb5);
average.innerHTML = 'Average: ' + (total / 5);
}
</script>
</head>
<form id="number">
<body>
First Number: <input type="text" name="numb1" onkeyup="getTotal ();" />
Second Number: <input type="text" name="numb2" onkeyup="getTotal();" />
Third Number: <input type="text" name="numb3" onkeyup="getTotal();" />
Fourth Number: <input type="text" name="numb4" onkeyup="getTotal();" />
Fifth Number: <input type="text" name="numb5" onkeyup="getTotal();" />
<div id="total">Total: </div>
<div id="average">Average: </div>
</body>
</html>
答案 0 :(得分:1)
total / 5
,其中total
是您通过ID获取的元素。难怪它不起作用;)
此外,您可能想了解循环。迭代而不是numb1
到numb5
。
这样的事情可以很好地运作:
<fieldset id="numbers"><legend>Numbers</legend>
First number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br />
Second number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br />
Third number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br />
Fourth number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br />
Fifth number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" />
</fieldset>
<div id="total">Total: --</div>
<div id="average">Average: --</div>
<script type="text/javascript">
function getTotal() {
var inputs = document.getElementById('numbers').getElementsByTagName('input'),
count = inputs.length, i, total = 0;
for( i=0; i<count; i++) total += parseInt(inputs[i].value || "0",10);
document.getElementById('total').firstChild.nodeValue = "Total: "+total;
document.getElementById('average').firstChild.nodeValue = "Average: "+(total/count);
}
</script>
答案 1 :(得分:0)
在每个输入标记的末尾添加BR标记<br/>
并改变这个
average.innerHTML = 'Average: ' + ((numb1 + numb2 + numb3 + numb4 + numb5) / 5);