我盯着学习Javascript,我试图创建一个计算器,只是乘以2个数字,我在浏览器控制台中收到此错误。 有人可以帮忙吗?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calc</title>
<style>#result{position: relative; top: 5px;}</style>
</head>
<body>
<input type="number" id="first"> *
<input type="number" id="second">
<br>
<input type="submit" id="result" value="Check out" onclick="res()"></input> <span id="span"></span>
<script>
function res() {
var a = document.getElementById("first").value;
var b = document.getElementById("second").value;
var span = document.getElementById("span");
if(a != 0 && b !=0) {
span.innerHTML = a * b;
}
if(a = 0 || b = 0) {
span.innerHTML = "0"; // I know browser can do it automatically without 21 and 22 strings but i need that it works this way.
}
}
</script>
</body>
</html>
答案 0 :(得分:0)
首先,如果您要使用文本输入进行任何数学运算,则必须将它们转换为数字。您可以使用parseInt(num, 10)
或parseFloat(num)
。
其次,在您的一个if语句中,您实际上并未比较变量a
和b
,而是为它们分配0
。使用两个等号==
来比较变量。
第三,您可以使用isNaN(num)
检查它们是否为数字。这样做会消除第一个if语句。
function res() {
var a = parseFloat(document.getElementById("first").value);
var b = parseFloat(document.getElementById("second").value);
var span = document.getElementById("span");
if (isNaN(a) || isNaN(b)) {
span.innerHTML = "0";
}
else {
span.innerHTML = a * b;
}
}
&#13;
<input type="number" id="first">*
<input type="number" id="second">
<br>
<input type="submit" id="result" value="Check out" onclick="res()"></input> <span id="span"></span>
&#13;
答案 1 :(得分:-1)
在此处查看您的更正代码
<html>
<head>
<title>Calc</title>
<style>#result{position: relative; top: 5px;}</style>
</head>
<body>
<input type="number" id="first"> *
<input type="number" id="second">
<br>
<input type="submit" id="result" value="Check out" onclick="res()"></input> <span id="span"></span>
<script>
function res() {
var a = document.getElementById("first").value;
var b = document.getElementById("second").value;
var span = document.getElementById("span");
if(a != 0 && b !=0) {
span.innerHTML = a * b;
}
if(a == 0 || b == 0) {
span.innerHTML = "0"; // I know browser can do it automatically without 21 and 22 strings but i need that it works this way.
}
}
</script>
</body>
</html>