简体   繁体   中英

Problem with javascript and user-input on website to make a darkmode switch

As you can see, I have a javascript which is supposed to make a darkmode switch on a website. javascript works I get the alert but nothing happens when I press the switch. Why? Note: I am very new to programming and stuff, so explanations for an idiot would be great. ----example.html----

  <a href="#" class="right">
    <button type="button" onclick="func()">Darkmode</button>
  </a>

---script.js---

let darkmode = 0
function func() {
    if(darkmode = 0){
        document.getElementById("main").style.background = "grey";
        document.getElementById("row").style.background = "grey";
        document.getElementById("footer").style.background = "grey";
        darkmode = 1;}
    else{
        document.getElementById("main").style.background = "white";
        document.getElementById("row").style.background = "white";
        document.getElementById("footer").style.background = "white";
        darkmode = 0;}
  }
alert("11 hot singles in your area");

----style.css---- (fe the main stuff from css)

  /* Main column */
  .main {   
    -ms-flex: 70%; /* IE10 */
    flex: 70%;
    background-color: white;
    padding: 20px;
  }

You got a very funny bug there

instead of if (darkmode = 0)

it should be if (darkmode === 0)

and that is just it

There is an error in your js that when you compare you should put == instead of = . SO your js will be:

 let darkmode = 0 function func() { if(darkmode == 0){ document.getElementById("main").style.background = "grey"; document.getElementById("row").style.background = "grey"; document.getElementById("footer").style.background = "grey"; darkmode = 1;} else{ document.getElementById("main").style.background = "white"; document.getElementById("row").style.background = "white"; document.getElementById("footer").style.background = "white"; darkmode = 0;} } alert("11 hot singles in your area");

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