1. 程式人生 > >網頁html錯誤:Uncaught TypeError: Cannot read property 'addEventListener' of null

網頁html錯誤:Uncaught TypeError: Cannot read property 'addEventListener' of null

<head>
<meta charset="utf-8">
<title>菜鳥教程(runoob.com)</title>
<script>
    document.getElementById("myBtn").addEventListener("click", function(){
    document.getElementById("demo").innerHTML = "Hello World";
   });
</script>

</head>
<body>

    <p>該例項使用 addEventListener() 方法來向按鈕新增點選事件。</p>
    <button id="myBtn">點我</button>
    <p id="demo"></p>

</body>
</html>

 

標籤元素還沒有建立就呼叫引用標籤的指令碼就會出現此問題,將指令碼放置在指令碼標籤的後面就可以了

<head>
<meta charset="utf-8">
<title>菜鳥教程(runoob.com)</title>
</head>

<body>
<p>該例項使用 addEventListener() 方法來向按鈕新增點選事件。</p>
<button id="myBtn">點我</button>
<p id="demo"></p>

<script>
    document.getElementById("myBtn").addEventListener("click", function(){
    document.getElementById("demo").innerHTML = "Hello World";
    });
</script>

</body>
</html>