无法读取 HTML 和 JavaScript 中的空 属性
Cannot read property of null in HTML and JavaScript
我是 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 Uncaught TypeError: Cannot read property 'style' of null
在 body 加载
后执行脚本
<!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>
我是 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 Uncaught TypeError: Cannot read property 'style' of null
在 body 加载
后执行脚本<!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>