我的按钮不响应我的事件侦听器?



下面是我的代码。我试图生成一个随机的十六进制颜色,将取代背景颜色,当我的按钮被点击,但我不能让它工作。

index . html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Color Changer</title>
</head>
<body>
<h1>
<button id="newColor">Click Me</button>
</h1>
</body>
</html>

scripts.js

const btn = document.getElementById("newColor");
btn.addEventListener("click", function onClick(event) {
let randColor = "#" + Math.floor(Math.random()*16777215).toString(16);
document.body.style.backgroundColor = randColor;
});
  1. 包含js文件到html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Color Changer</title>
<script src="scripts.js"></script>
</head>
<body>
<h1>
<button id="newColor">Click Me</button>
</h1>
// or include here
//<script src="scripts.js"></script>
</body>
</html>
  1. 可以使用事件onload的js相同:
window.onload = function () {
const btn = document.getElementById("newColor");
btn.addEventListener("click", function onClick(event) {
let randColor = "#" + Math.floor(Math.random()*16777215).toString(16);
document.body.style.backgroundColor = randColor;
});
};
  1. 可以使用jquery $(document).ready()

代码是工作是你的js代码是HTML标签后?

const btn = document.getElementById("newColor");
btn.addEventListener("click", function onClick(event) {
let randColor = "#" + Math.floor(Math.random()*16777215).toString(16);
document.body.style.backgroundColor = randColor;
});
<h1>
<button id="newColor">Click Me</button>
</h1>

最新更新