gpt4 book ai didi

JavaScript 计算器脚本不起作用

转载 作者:行者123 更新时间:2023-12-02 14:55:30 27 4
gpt4 key购买 nike

我正在学习 JavaScript。尝试使用 DOM 制作一个简单的计算器。我写了下面的脚本,但我的脚本给出了错误。未捕获的类型错误:无法读取空calculator.html的属性“值”:8

这是我的脚本:

    <!DOCTYPE html>
<html>
<head>
<title>My Calculator</title>
</head>
<body>
<script type="text/javascript">
var f_number = document.getElementById("f_number").value;
var f_number = document.getElementById("s_number").value;

function calculate(opa)
{
if(opa=='+')
{
var result = Number(f_number) + Number(s_number);
}
if(opa=='-')
{
var result = f_number - s_number;
}
if(opa=='*')
{
var result = f_number * s_number;
}
if(opa=='/')
{
var result = f_number / s_number;
}
return document.getElementById('res').value = result;
}
</script>
<div class="container">
<table>
<tr>
<td>First Number</td>
<td><input type="number" id="f_number" ></td>
</tr>
<tr>
<td>Second Number</td>
<td><input type="number" id="s_number" ></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="+" onclick="calculate()" >
<input type="submit" value="-" onclick="calculate()" >
<input type="submit" value="*" onclick="calculate()" >
<input type="submit" value="/" onclick="calculate()" >
</td>
</tr>
<tr>
<td>Result</td>
<td><input type="text" id="res"></td>
</tr>
</table>
</div>
</body>
</html>

最佳答案

工作代码的完整示例:

<!DOCTYPE html>
<html>
<head>
<title>My Calculator</title>
</head>
<body>
<div class="container">
<table>
<tr>
<td>First Number</td>
<td><input type="number" id="f_number" ></td>
</tr>
<tr>
<td>Second Number</td>
<td><input type="number" id="s_number" ></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="+" onclick="calculate('+')" >
<input type="submit" value="-" onclick="calculate('-')" >
<input type="submit" value="*" onclick="calculate('*')" >
<input type="submit" value="/" onclick="calculate('/')" >
</td>
</tr>
<tr>
<td>Result</td>
<td><input type="text" id="res"></td>
</tr>
</table>
</div>
<script type="text/javascript">
function calculate(opa)
{
var f_number = +document.getElementById("f_number").value;
var s_number = +document.getElementById("s_number").value;
if(opa=='+')
{
var result = f_number + s_number;
}
if(opa=='-')
{
var result = f_number - s_number;
}
if(opa=='*')
{
var result = f_number * s_number;
}
if(opa=='/')
{
var result = f_number / s_number;
}
return document.getElementById('res').value = result;
}
</script>
</body>
</html>

关于JavaScript 计算器脚本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35849155/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com