首页 > 解决方案 > TypeError:无法读取 null 的属性 [在调用外部(延迟)/内部 JSFile 时]

问题描述

下面的 Html/JS(vanilla) 脚本给出了以下错误[当与内部脚本以及外部 JS 文件一起使用时(使用“defer”关键字)] -
如何解决此错误?

铬合金

Uncaught TypeError: Cannot read property 'onclick' of null  

火狐

TypeError: document.getElementById(...) is null  

//StackOverflow Error - Filename empty (Not sure how to insert JS filename?).But this script works fine on Local codeeditor(VsCode).

document.getElementById("change1").onclick(function(){
  
    document.getElementById("tx1").innerHTML = "tx1 changed with JS";
 console.log("Change1  btn pressed");   
    }
)

document.querySelector("change2").addeventlistener("click",()=>{
  
    document.getElementById("tx2").innerHTML = "tx2 changed with JS";
 console.log("Change2 btn pressed");   
    },false
)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=<<device-width>>, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Event2</title>
    <script src= "testJS_event2.js" defer ></script>
    

</head>
<body>
 <div>
     
     <p id="tx1">tx1 <--- this element is null </p>
     <h1 id="tx2">tx2 <--- this element is also null  </h1><br>
     <button id = "change1">Change1</button>
     <button id = "change2">Change2</button>
 </div>   
</body>
</html>

标签: javascriptdom

解决方案


您的问题是 Javascript 在您的页面完全加载之前执行,因此它可以找到您的元素。

使用window.onload()会很好!

或者你可以把你<script src= "testJS_event2.js" defer ></script>的放在身体的末端(更好的加载时间解决方案)


推荐阅读