【问题标题】:Local storage not working properly for JS onclickJS onclick 的本地存储无法正常工作
【发布时间】:2022-01-11 03:51:43
【问题描述】:

我的本​​地存储在判断真假方面工作,但是当页面刷新时,它会恢复但保留值。例如,如果我从默认的暗模式(假)切换到亮模式(真),它在本地存储中显示为真(这很好)。但是,当我刷新页面时,尽管该值仍然为 true,但页面已恢复为默认值 (false)。

HTML:

<body onload="stored()">
  <label for="ID_HERE" class="toggle-switchy">
    <input checked type="checkbox" name="server" id="ID_HERE" />
    <span class="toggle" onclick="toggle()" id="saveDarkLight"></span>
    <span class="switch"></span>
  </label>
</body>

JS:

function stored() {
  var storedValue = localStorage.getItem("server");
  if (storedValue) {
    lightmode()
    document.getElementById("ID_HERE").checked = true;
  } else {
    darkmode()
    document.getElementById("ID_HERE").checked = false;
  }
}

function toggle() {
  if (document.getElementById("ID_HERE").checked) {
    lightmode()
    var input = document.getElementById("ID_HERE");
    localStorage.setItem("server", input.checked);
  }
  else {
    darkmode()
    var input = document.getElementById("ID_HERE");
    localStorage.setItem("server", input.checked);
  }
}

function darkmode() {
  const bodyChanges = document.querySelectorAll('.margin_body');
  for (let i = 0; i < bodyChanges.length; i++) {
    bodyChanges[i].style.background = '#0c0a0f';
  }
}

function lightmode() {
  const bodyChanges = document.querySelectorAll('.margin_body');
  for (let i = 0; i < bodyChanges.length; i++) {
    bodyChanges[i].style.background = 'white';
  }
}

【问题讨论】:

    标签: javascript onclick local-storage


    【解决方案1】:

    localStorage 只保存string 值,因此保存truefalse 会将其转换为'true''false'。 回读时,您需要JSON.parse 或检查字符串值。

    function stored() {
        const storedValue = localStorage.getItem("server");
        if(storedValue === 'true'){  // <------
            lightmode()
            document.getElementById("ID_HERE").checked = true;
        }else{
            darkmode()
            document.getElementById("ID_HERE").checked = false;
        }
    }
    

    【讨论】:

    • Uncaught TypeError: Cannot set properties of null (setting 'checked') 这是在:document.getElementById("ID_HERE").checked = true;
    【解决方案2】:

    首先,我认为您需要在输入元素上使用 onclick 事件处理程序。

    此外,以下是一个快速而肮脏的实现:

    JS:

    const SAVED_USER_INPUT = "savedUserInput";
    const TARGET_ID = "toggle-text";
    const BLUE = "blue";
    const RED = "red";
    const text = {
      [BLUE]:
        "Text color currently set to blue (default/unchecked state). Click to change to red",
      [RED]: "Text color currently set to red. Click to change to blue",
    };
    
    const handleToggle = (event) => {
      const isChecked = event.target.checked;
      const color = isChecked ? RED : BLUE;
      setColor(color);
      setText(color);
      savePreference(color);
    };
    
    const setColor = (fontColor = BLUE) => {
      document.getElementById(TARGET_ID).style.color = fontColor;
      return true;
    };
    const setText = (color) => {
      document.getElementById(TARGET_ID).innerText = text[color];
      return true;
    };
    const setChecked = (color) => {
      if (color === RED) {
        document.getElementsByTagName("input")[0].setAttribute("checked", true);
      }
    };
    const savePreference = (color) => localStorage.setItem(SAVED_USER_INPUT, color);
    const getSavedPreference = () => localStorage.getItem(SAVED_USER_INPUT);
    // localStorage.clear()
    window.onload = () => {
      if (!(getSavedPreference() === null)) {
        const savedColor = getSavedPreference();
        setColor(savedColor);
        setText(savedColor);
        setChecked(savedColor);
      } else {
        setColor();
        setText(BLUE);
        setChecked(BLUE);
      }
    };
    

    HTML:

    <!DOCTYPE html>
    <html>
    
    <head>
        <title>localStorage</title>
        <script src="app.js"></script>
    </head>
    
    <body>
        <label>
            <input type="checkbox" onclick="handleToggle(event)">
            <span id="toggle-text"></span>
            </span>
        </label>
    </body>
    
    </html>
    

    【讨论】:

      猜你喜欢
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多