0

我不能让一切都集中。这就是我得到的:

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>
4

2 回答 2

1

total / 5total您通过 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>
于 2013-02-14T00:01:30.383 回答
0

<br/>在每个输入标签的末尾添加 BR 标签并更改它

average.innerHTML = 'Average: ' + ((numb1 + numb2 + numb3 + numb4 + numb5) / 5);
于 2013-02-14T00:06:01.510 回答