0

我需要在表单下方的跨度中显示 2 个数字的输出(和、差、积、商)。我尝试了很多变化,但根本无法显示总和等。请帮助我是一个Javascript菜鸟!!!谢谢!

 function calculate() {
'use strict';

// Read the first text box and convert to a float
var input = document.getElementById('number1').value;
var number1 = parseInt(input);


var input = document.getElementById('number2').value;
var number2 = parseInt(input);


// Calculations 
sum = number1 + number2;
difference = number1 - number2;
product = number1 * number2;
quotient = number1 / number2;

// Display the results in relevant spans
document.getElementById('sum').value = sum;
document.getElementById('difference').value = difference;
document.getElementById('product').value = product;
document.getElementById('quotient').value = quotient;


return false;

} 


function init() {
'use strict';
    document.getElementById('theForm').onsubmit = calculate;
} 
window.onload = init;

HTML

<form action="" method="post" id="theForm">
    <fieldset>
        <div><label for="number1">Number 1</label>
            <input type="text" name="number1" id="number1" required>
        </div>
        <div><label for="number2">Number 2</label>
            <input type="text" name="number2" id="number2" required>
        </div>
        <br />
        <div><input type="submit" value="Calculate"></div>
    </fieldset>
</form>

<span id="sum"></span><br />
<span id="difference"></span><br /> 
<span id="product"></span><br />
<span id="quotient"></span><br />
4

1 回答 1

1

要将值分配给 span 标签,我们需要使用innerHTML属性,而不是value.

document.getElementById('sum').innerHTML = sum;
document.getElementById('difference').innerHTML = difference;
document.getElementById('product').innerHTML = product;
document.getElementById('quotient').innerHTML = quotient;

和改变

<form action="" method="post" id="theForm">

<form action="" method="post" id="theForm" onsubmit="return calculate()">

您只需calculate在表单提交时调用该函数。

于 2013-10-20T02:40:35.377 回答