简体   繁体   中英

How to change the colour of the button with JavaScript multiple times?

can you please help me with the following. I have a button which I want to change the color on click. After the first click, I want the color to change to "red". But then (when the button is already red), I want to change the color of the same button to "green".

Here's my code I'm trying to write, however, only the first part works (after the first click the button becomes red). How should I adjust it so that on the second click the button color changes to green? Thank you so much!

 let element = document.querySelector("button"); function turnButtonRed () { element.style.backgroundColor = 'red'; element.style.color = 'white'; element.innerHTML = 'Red Button'; element.onclick = turnButtonRed; } function turnButtonGreen(){ element.style.backgroundColor = 'green'; element.style.color = 'white'; element.innerHTML = 'Green Button'; } function greenButton(){ if (element.innerHTML === 'Red Button'){ element.onclick = turnButtonGreen(); } else { element.onclick = turnButtonRed; } } };

 function changeColor() { const color = document.getElementById("b1").style.backgroundColor; switch (color){ case "": document.getElementById("b1").style.backgroundColor = "red"; break; case "red": document.getElementById("b1").style.backgroundColor = "green"; break; } }
 <button id="b1" onclick="changeColor()">Change Color</button>

<!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>Cick me </button>
<script>
    let element = document.querySelector("button");
    element.onclick = turnButtonRed;
    let flag = true;

    function turnButtonRed() {
        if (flag === true) {
            element.style.backgroundColor = 'red';
            element.style.color = 'white';
            element.innerHTML = 'Red Button';
            flag = false;
        } else if (flag === false) {
            element.style.backgroundColor = 'green';
            element.style.color = 'white';
            element.innerHTML = 'Green Button';
            flag = true;
        }


    }
  </script>
  </body>

 </html>

I have just put a flag which is responsible for controlling the alternating the color of the button. I hope it will solve your problem

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