JavaScript 加法运算错误排查及修复:为何结果始终失败?
这段代码中,top1 的值加上 top2 的值应该等于 top3,但为何反馈的是 else 的结果内容?
在代码中,虽然定义了变量 top1、top2 和 top3,但在给它们赋值时出现了错误。代码中三个变量都被赋值为 document.getElementById("top3"),而正确的赋值应该分别为 document.getElementById("top1")、document.getElementById("top2") 和 document.getElementById("top3")。因此,在进行判断时,top1 和 top2 的值都为 undefined,导致无法进行正确的计算。
修改代码如下:
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function(){
var top1 = document.getElementById('top1');
var top2 = document.getElementById('top2');
var top3 = document.getElementById('top3');
var panduan = document.getElementById('panduan');
panduan.onclick = function(){
if(Number(top1.value)+Number(top2.value) == top3.value){
alert('您已经成功了');
}else{
alert('你彻底失败了');
}
}
}
</script>
<meta charset="UTF-8" />
<title>JavaScript 加法运算错误排查及修复</title>
</head>
<body>
<input type="" name="">
<input type="button" name="" value="+" id="top1">
<input type="" name="">
<input type="button" name="" value="=" id="top2">
<input type="number" name="" id="top3">
<br>
<input type="" name="">
<input type="button" name="" value="+" id="top4">
<input type="" name="">
<input type="button" name="" value="=" id="top5">
<input type="" name="">
<br>
<input type="button" name="" value="查询结果" id="panduan">
</body>
</html>
修改后的代码将能够正确判断输入的值是否等于 top1 和 top2 的和。
原文地址: https://www.cveoy.top/t/topic/oiqI 著作权归作者所有。请勿转载和采集!