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表示页面加载完成后执行的函数

猜你喜欢

转载自blog.csdn.net/hl_qianduan/article/details/81126270