简体   繁体   中英

JavaScript Event (click), on each click

I'm trying to change the background color on each click.

var button = document.querySelector("button");
var body = document.querySelector("body");
var color = true;

button.addEventListener("click", function(){
    if(color){
        body.style.backgroundColor = "purple";
        color != color;
    }
    else if (!color){
        body.style.backgroundColor = "green";
    }
});

A small modification. You need to toggle the variable on every click. You could simplify your code further by getting rid of the if else and replace it with else

var button = document.querySelector("button");
var body = document.querySelector("body");
var color = true;

button.addEventListener("click", function() {
  if (color) {
    body.style.backgroundColor = "purple";
  } else {
    body.style.backgroundColor = "green";
  }
  // or equivalent with a ternary operator:
  body.style.backgroundColor = color ? "purple" : "green";

  // color != color is a comparison, but you want an assignment:
  color = !color;
});

Check Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM