单击“Javascript中的事件不起作用”

时间:2016-03-11 21:38:11

标签: javascript

此程序应该从给定的颜色数组中更改HTML正文的背景颜色。但颜色没有出现,应该是什么?

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

<head>
    <meta charset="UTF-8">
    <title>I Can Click A Rainbow</title>
</head>

<body>
    <button id="button">click me</button>
    <script src="js/script.js"></script>
</body>

</html>

    var button = document.getElementById("button");

var rainbow = ["red", "orange", "green", "blue", "indigo", "violet"];

function change() {
    "use strict";

    document.body.style.background = rainbow[Math.floor(7 * Math.random())];
}

button.addEventListener("click change");

1 个答案:

答案 0 :(得分:2)

Here is a working example

你这里有一个错字:

button.addEventListener("click change");

确保将您的功能包含在功能中,而不是字符串的一部分!

button.addEventListener("click", change);