Jas*_*aft 1 javascript forms math function getelementbyid
我的想法是,我应该有两个字段,我输入数字,然后我需要显示总和以及产品.
我想我会测试产品,但我不断收到"非数字"错误.任何帮助都会很棒!
<!DOCTYPE html>
<html>
<body>
<form>
First Number<br>
<input id="num1" type="text" name="num1">
<br>
Second Number:<br>
<input id="num2" type="text" name="num2">
<br><br>
<input type="button" value="Do Maths" onclick="doMath();" />
</form>
<script>
function doMath() {
var numOne = document.getElementById('num1').value;
var numTwo = document.getElementById('num2').value;
var theProduct = parseInt(my_input1) * parseInt(my_input2); document.write(theProduct);
document.write(theProduct);
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
你有my_input1和my_input2哪些没有定义.
改变这一行:
var theProduct = parseInt(my_input1) * parseInt(my_input2); document.write(theProduct);
这应该是正确的行:
var theProduct = parseInt(numOne) * parseInt(numTwo); document.write(theProduct);
显然,如果你想要总和:
var theTotal = parseInt(numOne) + parseInt(numTwo);
并打印出来: document.write(theTotal);
另外, 我想在我的回答中添加一个东西.如果您只是在测试,请改用它并在控制台中查看它:
console.log("Product: " + theProduct);
console.log("Total: " + theTotal);
Run Code Online (Sandbox Code Playgroud)
如果您按照自己的方式写文档,那么您将删除所有内容,这意味着您需要刷新每个输入.不确定你是否意识到这一点.无论如何,这是参考的功能.
function doMath() {
var numOne = document.getElementById('num1').value;
var numTwo = document.getElementById('num2').value;
var theProduct = parseInt(numOne) * parseInt(numTwo);
var theTotal = parseInt(numOne) + parseInt(numTwo);
// document.write(theProduct);
// document.write(theTotal);
console.log("Product: " + theProduct);
console.log("Total: " + theTotal);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2614 次 |
| 最近记录: |