<script>          window.onload = function () {              var btn = document.querySelector("button");              btn.onclick = function getHealth() {                  var i1 = document.querySelector("input:nth-child(1)");                  var i2 = document.querySelector("input:nth-child(2)");                  var i3 = document.querySelector("input:nth-child(3)");                  var v1 = i1.value;                  var v2 = i2.value;                  var v3 = i3.value;                    console.log(v1);                  console.log(v2);                  console.log(v3);              }          }      </script>      <input type="text" placeholder="性别(男/女)"><br>      <input type="text" placeholder="身高(cm)"><br>      <input type="text" placeholder="体重(kg)"><br>      <button>评估</button>  Cannot read properties of null (reading 'value')      at HTMLButtonElement.getHealth   为啥获取不到这个值 这个错误发生在获取输入框的值时,可能是因为在获取输入框之前,脚本在页面加载之前运行了。可以尝试将脚本放在页面底部,或者将脚本包裹在DOMContentLoaded事件中,以确保脚本在页面加载完毕后再执行。例如:
<pre><code class="language-html">&lt;script&gt;
    document.addEventListener(&quot;DOMContentLoaded&quot;, function() {
        var btn = document.querySelector(&quot;button&quot;);
        btn.onclick = function getHealth() {
            var i1 = document.querySelector(&quot;input:nth-child(1)&quot;);
            var i2 = document.querySelector(&quot;input:nth-child(2)&quot;);
            var i3 = document.querySelector(&quot;input:nth-child(3)&quot;);
            var v1 = i1.value;
            var v2 = i2.value;
            var v3 = i3.value;
            console.log(v1);
            console.log(v2);
            console.log(v3);
        }
    });
&lt;/script&gt;
</code></pre>
<p>这样应该能够解决获取不到值的问题。</p>
JavaScript 错误:Cannot read properties of null (reading 'value') 解决方法

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

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