为什么我的函数改变背景颜色运行(警报有效),但颜色没有改变?

Why is my function to change the background color run (alert works), but does not change the color?

目前正在学习Javascript,完全是新手。尝试编写一个函数,当单击按钮时,将 <body> 元素的背景颜色从白色切换为紫色,反之亦然。

警报正在运行,因此功能正在 运行,但颜色从未改变。

完全不知道发生了什么...

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
  <title>My Title</title>

</head>
<body>>
  <button>Click me!</button>

  <h1>I am an h1!</h1>
    <p id="first" class="special">Hello</p>
    <p class="special">Goodbye</p>
    <p>Hi Again</p>
  <p id="last">Goodbye Again</p>
  

  <!-- SCRIPS -->
  <script type="text/javascript" src="exercises.js"></script>
</body>
</html>

JavaScript:

var color_button = document.querySelector("button");
var is_purple = false;

color_button.addEventListener("click", function() {
    alert("clicked");
    if (is_purple = false) {
        document.querySelector("body").style.backgroundColor = "purple";
        is_purple = true;
    }
    else {
        document.querySelector("body").style.backgroundColor = "white";
        is_purple = false;
    }
});

您的问题是您在比较器中使用了单个 equals。单等号是给变量赋值,不是比较。

color_button.addEventListener("click", function() {
    alert("clicked");
//what you had
//    if (is_purple = false) {
//what it should be
      if (is_purple === false) {
        document.querySelector("body").style.backgroundColor = "purple";
        is_purple = true;
    }
    else {
        document.querySelector("body").style.backgroundColor = "white";
        is_purple = false;
    }
});