添加addEventListener触发Uncaught TypeError:无法读取null属性的技术求助
Hey there! Let's break down why you're hitting this error and how to fix it quickly.
The Root Cause
Your JavaScript code is running in the <head> section of your HTML. When the browser executes this line:
var diascawf = document.getElementById("b1")
the browser hasn't finished rendering the <body> yet—so the element with ID b1 doesn't exist in the DOM at that point. That's why document.getElementById returns null, and trying to call addEventListener on null throws the TypeError you're seeing.
Easy Fixes
1. Move your script to the end of the <body>
This is the simplest approach. By placing your script right before the closing </body> tag, you ensure all DOM elements are loaded before your code runs:
<!-- Bootstrap core JavaScript --> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Your custom script here --> <script type="text/javascript"> var game = ["N" , "N", "N", "N", "N", "N", "N", "N", "N"]; var gamen = [0, 0, 0, 0, 0, 0, 0, 0, 0]; var cs = 0; var score1 = 0; var score2 = 0; var diascawf = document.getElementById("b1") diascawf.addEventListener("click", doSet) function doSet(){ alert("Hello World") } </script> </body> </html>
2. Use DOMContentLoaded event
If you prefer keeping your script in the <head>, wrap your code in a listener for the DOMContentLoaded event. This event fires when the initial HTML is fully loaded and parsed:
<script type="text/javascript"> var game = ["N" , "N", "N", "N", "N", "N", "N", "N", "N"]; var gamen = [0, 0, 0, 0, 0, 0, 0, 0, 0]; var cs = 0; var score1 = 0; var score2 = 0; document.addEventListener('DOMContentLoaded', function() { var diascawf = document.getElementById("b1") diascawf.addEventListener("click", doSet) }); function doSet(){ alert("Hello World") } </script>
3. Add the defer attribute to your script tag
Adding defer tells the browser to download the script in the background but execute it only after the DOM is fully parsed:
<script type="text/javascript" defer> var game = ["N" , "N", "N", "N", "N", "N", "N", "N", "N"]; var gamen = [0, 0, 0, 0, 0, 0, 0, 0, 0]; var cs = 0; var score1 = 0; var score2 = 0; var diascawf = document.getElementById("b1") diascawf.addEventListener("click", doSet) function doSet(){ alert("Hello World") } </script>
Any of these methods will ensure your script can find the b1 element before trying to attach the event listener, fixing the error.
内容的提问来源于stack exchange,提问作者user9143162

