首页 > 解决方案 > 无法读取 HTML 和 JavaScript 中的 null 属性

问题描述

我是 JS 新手。我试图制作一个按钮来改变 HTML 页面的 BG 颜色。这是 HTML 代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="js/index.js"></script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button class="btn btn-outline-secondary">Click Me!</button>
</body>
</html>

这是JS:

const button = document.querySelector('button');
const body = document.querySelector('body');
const colors = ['red', 'green', 'blue', 'yellow', 'pink', 'purple'];

body.style.backgroundColor = 'violet';
button.addEventListener('click', changeBackground);

function changeBackground(){
const colorIndex= parseInt(Math.random()*colors.length);
body.style.backgroundColor = colors[colorIndex];
}

此代码不起作用,并且在控制台上不断出错

index.js:5 未捕获的类型错误:无法读取 null 的属性“样式”

标签: javascripthtmldom-events

解决方案


在你的身体加载后执行你的脚本

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button class="btn btn-outline-secondary">Click Me!</button>
    <script src="js/index.js"></script>
</body>

</html>

推荐阅读