<!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>&lt;input type=&quot;text&quot; name=&quot;&quot; id=&quot;top1&quot;&gt;
&lt;input type=&quot;text&quot; name=&quot;&quot; id=&quot;top2&quot;&gt;
&lt;input type=&quot;text&quot; name=&quot;&quot; id=&quot;top3&quot;&gt;
</code></pre>
<p><strong>修改后的代码如下:</strong></p>
<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;meta charset=&quot;UTF-8&quot; /&gt;
  &lt;title&gt;title&lt;/title&gt;
  &lt;script&gt;
    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('你彻底失败了');
      }
    }
  &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;input type=&quot;text&quot; name=&quot;&quot; id=&quot;top1&quot;&gt;
  &lt;input type=&quot;button&quot; name=&quot;&quot; value=&quot;+&quot; &gt;
  &lt;input type=&quot;text&quot; name=&quot;&quot; id=&quot;top2&quot;&gt;
  &lt;input type=&quot;button&quot; name=&quot;&quot; value=&quot;=&quot; &gt;
  &lt;input type=&quot;text&quot; name=&quot;&quot; id=&quot;top3&quot;&gt;
  &lt;br&gt;
  &lt;input type=&quot;text&quot; name=&quot;&quot;&gt;
  &lt;input type=&quot;button&quot; name=&quot;&quot; value=&quot;+&quot; &gt;
  &lt;input type=&quot;text&quot; name=&quot;&quot;&gt;
  &lt;input type=&quot;button&quot; name=&quot;&quot; value=&quot;=&quot; &gt;
  &lt;input type=&quot;text&quot; name=&quot;&quot;&gt;
  &lt;br&gt;
  &lt;input type=&quot;button&quot; name=&quot;&quot; value=&quot;查询结果&quot;&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
JavaScript 代码报错:元素 ID 未找到,如何修改?

原文地址: https://www.cveoy.top/t/topic/oiqp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录