javascript - 无法读取 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 的属性“样式”
解决方案
在你的身体加载后执行你的脚本
<!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>
推荐阅读
- java - Eclipse SpringTestSuite 4/Spring Boot 2 Maven 如何在运行测试时排除类执行?
- jenkins - 在 Jenkins Pipeline 的 shell 脚本部分定义变量
- javascript - 如何在打印视图中显示 Jquery 数据表信息?
- kentico - 当他/她访问某个页面时注销用户
- angular - Angular 4模板可变焦点
- c# - 如何使用 Firebase 统一创建 Facebook 登录?
- r - 避免在 R 中的 file.copy 中覆盖
- r - R回归分析:分析某个种族的数据
- sql - SQL groupby 具有不同的计数
- jquery - 具有多个拆分导航的 Bootstrap 4 Navbar 不会折叠