JavaScript 代码调试:解决加法运算结果错误问题
这段代码有两个问题:
-
输入框中没有指定输入类型,应该将第一个和第三个输入框的 type 属性设置为 number,否则会出现 NaN 的情况。
-
第二个加号按钮的 id 应该是'top4' 而不是'top2'。
修改后的代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>title</title>
<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>
</head>
<body>
<input type="number" name="">
<input type="button" name="" value="+" id="top1">
<input type="number" name="" id="top2">
<input type="button" name="" value="=" id="top4">
<input type="number" name="" id="top3">
<br>
<input type="number" name="">
<input type="button" name="" value="+" id="top5">
<input type="number" name="">
<input type="button" name="" value="=" id="top6">
<input type="number" name="">
<br>
<input type="button" name="" value="查询结果" id="panduan">
</body>
</html>
通过修改输入框类型和按钮 ID,代码能够正确执行加法运算,并根据结果显示不同的提示信息。
原文地址: https://www.cveoy.top/t/topic/oiqU 著作权归作者所有。请勿转载和采集!