我在javascript中锻炼并且我已经制作了这个脚本以便计算2个变量的总和,然后在第三个等式中使用这个总和!关于如何完成这项工作的任何想法都将非常有用!
<form name="Calcultor" Method="Get" id='form1'>First Number:
<input type="text" name="fnum" size="35" id="first">+ Second Number:
<input type="text" name="snum" size="35" id="sec">
<br>
<br>Answer:
<input type="text" name="ans" size="35" id="ans" />
<input type="text" name="ans2" size="35" id="ans2" />
<button type="button" onclick="Calculate();">Calculate</button>
</form>
<script lang="javascript">
function Calculate() {
var first = document.getElementById('first').value;
var sec = document.getElementById('sec').value;
var ans = document.getElementById('ans').value;
document.getElementById('ans').value = parseInt(first) + parseInt(sec);
document.getElementById('ans2').value = parseInt(ans);
document.form1.submit();
}
</script>
&#13;
提前致谢!
答案 0 :(得分:1)
这是:
function Calculate() {
var first = document.getElementById('first').value;
var sec = document.getElementById('sec').value;
var ans = document.getElementById('ans').value;
document.getElementById('ans').value = parseInt(first) + parseInt(sec);
document.getElementById('ans2').value = document.getElementById('ans').value;
/*document.form1.submit();*/
}
<form name="Calcultor" Method="Get" id='form1'>First Number:
<input type="text" name="fnum" size="35" id="first">+ Second Number:
<input type="text" name="snum" size="35" id="sec">
<br>
<br>Answer:
<input type="text" name="ans" size="35" id="ans" />
<input type="text" name="ans2" size="35" id="ans2" />
<button type="button" onclick="Calculate();">Calculate</button>
</form>
如果有什么不清楚的话,请随意询问!
更新(将最后一个输入值加1):
function Calculate() {
var first = document.getElementById('first').value;
var sec = document.getElementById('sec').value;
var ans = document.getElementById('ans').value;
document.getElementById('ans').value = parseInt(first) + parseInt(sec);
document.getElementById('ans2').value = parseInt(document.getElementById('ans').value) + 1;
/*document.form1.submit();*/
}
<form name="Calcultor" Method="Get" id='form1'>First Number:
<input type="text" name="fnum" size="35" id="first">+ Second Number:
<input type="text" name="snum" size="35" id="sec">
<br>
<br>Answer:
<input type="text" name="ans" size="35" id="ans" />
<input type="text" name="ans2" size="35" id="ans2" />
<button type="button" onclick="Calculate();">Calculate</button>
</form>
在对数字进行求和之前,您应该使用parseInt()
,而没有解析后的值,您将string
与number
求和,并且正如预期的那样,结果将是一个包含多个字符的字符串。