JavaScript 代码报错:元素 ID 未找到,如何修改?
<!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');
if(Number(top1.value)+Number(top2.value) == top3.value){
alert('您已经成功了');
}else{
alert('你彻底失败了');
}
}
</script>
</head>
<body>
<input type="text" name="" id="top1">
<input type="button" name="" value="+" >
<input type="text" name="" id="top2">
<input type="button" name="" value="=" >
<input type="text" name="" id="top3">
<br>
<input type="text" name="">
<input type="button" name="" value="+" >
<input type="text" name="">
<input type="button" name="" value="=" >
<input type="text" name="">
<br>
<input type="button" name="" value="查询结果">
</body>
</html>
<p>**错误原因:**在代码中没有找到 id 为 'top1'、'top2'、'top3' 的元素。</p>
<p>**修改方案:**在第13行代码之前添加以下代码,给输入框添加 id 属性。</p>
<pre><code><input type="text" name="" id="top1">
<input type="text" name="" id="top2">
<input type="text" name="" id="top3">
</code></pre>
<p><strong>修改后的代码如下:</strong></p>
<pre><code><!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');
if(Number(top1.value)+Number(top2.value) == top3.value){
alert('您已经成功了');
}else{
alert('你彻底失败了');
}
}
</script>
</head>
<body>
<input type="text" name="" id="top1">
<input type="button" name="" value="+" >
<input type="text" name="" id="top2">
<input type="button" name="" value="=" >
<input type="text" name="" id="top3">
<br>
<input type="text" name="">
<input type="button" name="" value="+" >
<input type="text" name="">
<input type="button" name="" value="=" >
<input type="text" name="">
<br>
<input type="button" name="" value="查询结果">
</body>
</html>
</code></pre>
原文地址: https://www.cveoy.top/t/topic/oiqp 著作权归作者所有。请勿转载和采集!