Uncaught TypeError: Cannot set property 'onclick' of null

報錯信息

要實現點擊button按鈕,紅色div消失

代碼如下

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script>
        var button = document.getElementById("button"),
            div = document.getElementById("div");
        button.onclick = function () {
            div.style.display = "none";
        };
    </script>
</head>
<body>
<button id="button">點擊我</button>
<div id="div" style="width: 100px;height: 100px;background:red;"></div>
</body>
</html>

錯誤原因:js代碼放在了<head>,放在<head>中的JS代碼是優先於頁面被執行的

修改方法:

方法一:把JS代碼放到</body>結束之前

方法二:把原本的JS代碼放入window.onload=function() { ... }中,window.onload表示頁面加載完成後執行的函數