javascript - 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>
解决方案
您的问题是 Javascript 在您的页面完全加载之前执行,因此它可以找到您的元素。
使用window.onload()会很好!
或者你可以把你<script src= "testJS_event2.js" defer ></script>
的放在身体的末端(更好的加载时间解决方案)
推荐阅读
- javascript - Java JSObject.eval() 不起作用,是否需要导入?
- html - 无法让图像响应?
- c - 如何在 C 中使用参数从文本文件中打印字符?
- javascript - 如何使用 AWS Cognito 对 API Gateway 进行身份验证
- docker - 如何将 C++ 库(例如 libjpeg-dev)添加到 Windows Docker Image 中,以便 CMake 可以检测到它们?
- amazon-web-services - 何时在 aws lambda 中使用 process.exit?
- ckan - 数据代理与数据预览
- java - Thymeleaf 在另一页上呈现一个页面错误
- android - 无法打印整个字符串值
- google-chrome - 在 Google Chrome 中测量数据传输?