javascript - 我不断收到 'Uncaught TypeError: Cannot read property ' value' of null' 响应,但不明白为什么

标签 javascript null typeerror

我意识到我可能正在寻找一些显而易见的东西,但到目前为止我似乎找不到它。我需要第二双眼睛。

<!DOCTYPE html>
<html>
    <head>
    <script type="text/javascript">
        var t;
        t=document.getElementById('temperture');
        var v;
        v=document.getElementById('speed');
        var h;
        h=document.getElementById('hum');
        function dpOnClick(){
          if (h.value < 50){
            alert('There is no dew point below 50% humidity');}
          else{
            document.getElementById('outputBox').innerHTML='The dew point would be '+  t.value - ((100 - (h.value)/100)/2.778);}

    return false;
    }

</script>
    <title> Weather Indexes </title>
</head>
<body>
    <h2>Weather Indexes</h2>
    <p> Enter degees in fahrenheit and select calculation.</p>
    <p> Degrees: <input type="number" id="temperture" size=12 value=''> °F </p>
    <p> Wind Speed: <input type="number" id="speed" size=12 value='' > mph </p>
    <p> Relative Humidity: <input type="number" id="hum" size=12 value='' ></p>

    <input type="button" value="Dew Point" onclick="dpOnClick();">

    <hr> <div id="outputBox"></div> </hr>
  </body>

</html>

最佳答案

将脚本放在 body 标记的末尾..

或输入以下行:

    t=document.getElementById('temperture');
    v=document.getElementById('speed');
    h=document.getElementById('hum');

进入window.onload

发生这种情况是因为 javascript 获取 DOM 时尚未创建,这就是它返回 null 或未定义的原因。

编辑

它的window.load不是document.window.load,抱歉拼写错误。

检查这个 fiddle 看看我的意思:https://jsfiddle.net/k3moqkkt/1/

如果您的脚本保留在 header 标记中,那就更好了。

关于javascript - 我不断收到 'Uncaught TypeError: Cannot read property ' value' of null' 响应,但不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31846003/

相关文章:

javascript - 未捕获 : TypeError

javascript - 使用 getElementsByClassName 而不是 getElementById 修改脚本以追加子项

javascript - 如何在 Javascript 中实现 map,其中值是一个类似于 Java 的字符串数组?

ruby-on-rails - Ruby on Rails session = 无

空字符串的 Java String hashCode

javascript - null 是 JavaScript 中的对象吗?

javascript - 未捕获的类型错误 : Object has no method 'contains'

jQuery 类型错误 : 'undefined' is not a function on AJAX submit

javascript - 在显示 JavaScript 中的绑定(bind)属性之前对其进行格式化

javascript - 使用 Javascript 上传 Codeigniter 图片