简体   繁体   中英

Function is not calling the correct function

I want to save a bool value for when you refresh the page, the value is true (if you want the color theme to be default, white) and false (if you want the color theme to be dark, black). Local storage is saving the last value correctly, and loading the correct value, but it is still not working, I don't know why. Here is my code, any help would be grateful.

var link = document.getElementById("color-mode");
var button = document.getElementById("theme-button");
var searchButton = document.getElementById("search-button");
var userSettings = document.getElementById("user-settings");
var siteLogo = document.getElementById("site-logo");
var isDefault = false;

button.onclick = function() {
    if(isDefault == true) {
        DarkTheme();
    }
    else {
        DefaultTheme();
    }
}

function DefaultTheme() {
    link.href = "../static/CSS/default.css";
    isDefault = true;
    searchButton.src = "../static/Media/SearchIconDefault.png";
    userSettings.src = "../static/Media/UserIconDefault.png";
    siteLogo.src = "../static/Media/LogoDefault.png";
    window.localStorage.setItem("saveTheme", isDefault);
}

function DarkTheme() {
    link.href = "../static/CSS/dark.css";
    isDefault = false;
    searchButton.src = "../static/Media/SearchIconDark.png";
    userSettings.src = "../static/Media/UserIconDark.png";
    siteLogo.src = "../static/Media/LogoDark.png";
    window.localStorage.setItem("saveTheme", isDefault);
}

function load() {
    isDefault = window.localStorage.getItem("saveTheme");
    console.log("Val: " + isDefault);
    if(isDefault == false) {
        DarkTheme();
    }
    else {
        DefaultTheme();
    }
}

load();

Read your code:

  1. load() initially had isDefault as false
  2. it calls DarkTheme , which sets isDefault also to false
  3. then user click button
  4. isDefault is false - then DarkTheme is called, which test isDefault also to false .

Application basically can't enter other theme, except the case where you change something manually in localStorage.

Change code to:

button.onclick = function() {
    if(isDefault == true) {
        DefaultTheme();
    }
    else {
        DarkTheme();
    }
}

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