如何使用javascript在刷新时保存切换按钮状态

问题描述

大家好,我在刷新页面时难以保持切换按钮的状态,它正确存储在 localStorage 中,但即使经过多次尝试,我仍无法调用该函数以在页面刷新时执行

save.addEventListener('click',() => {
    localStorage.setItem("checkbox1",checkBox1.checked);
    localStorage.setItem("checkbox2",checkBox2.checked);
    localStorage.setItem('timezone',timezone.selectedIndex);
  }

  function isChecked() {
    const checkBox1 = document.getElementById('checkbox1');
    if (document.getElementById('checkbox1').checked == false) {
      localStorage.getItem('checkbox1');
    }
  }

  window.onload = function() {
    isChecked();
  };
}
<form>
  <div class="toggle-switch-1">
    <p class="notification-1">Send Email Notifications</p>
    <!-- toggle switch goes here -->
    <label type="button" class="switch-light switch-candy">
        <input id="checkbox1" type="checkbox">
            <span>
                <span id="off">Off</span>
                <!-- <span id="on1">On</span> -->
                <!-- <button onclick="check()" id="on1">On</button> -->
                <span id="on1">On</span>
                <a></a>
            </span>
        </label>
  </div>

  <div class="toggle-switch-2">
    <p class="notification-2">Send Profile to Public</p>
    <!-- toggle switch goes here -->
    <label class="switch-light switch-candy" onclick="">
        <input id="checkbox2" type="checkbox">
            <span>
                <span id="off">Off</span>
                <span id="on2">On</span>
                <a></a>
            </span>
        </label>
  </div>

  <select class="form-field" id="timezone">
    <option disabled selected>Select Timezone</option>
    <option>Eastern Standard Time (EST)</option>
    <option>Pacific Standard Time (PST)</option>
    <option>Central Standard Time (CST)</option>
    <option>Mountain Standard Time (MST)</option>
  </select>

  <div class="settings-button">
    <button type="button" class="button-primary" id="save">Save</button>

    <button class="button-disabled" id="cancel">Cancel</button>
  </div>
</form>

我正在尝试在刷新时保存按钮的状态(单击保存按钮),但是当我刷新以及时区下拉列表时它默认为关闭,如果有人可以帮助解决这个问题,我将不胜感激 谢谢你!!

解决方法

您只是从本地存储中获取值。但实际上并未将其分配给任何切换按钮。您需要分配它们才能使其工作

function isChecked() {
  document.getElementById('checkbox1').checked = localStorage.getItem('checkbox1') === 'true');
}

这是它的工作原理:

  • 从本地存储中获取值。

  • 保存在本地存储中的值将是字符串类型。

  • 因此我们需要将其转换为布尔值才能使其工作。 === 检查将为您做到这一点。

  • 最后将其分配给复选框。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...