大家好,当我刷新页面时,我很难保持切换按钮的状态,它被正确地存储在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>
我正在尝试保存刷新按钮的状态(单击保存按钮),但它默认为关闭,当我刷新时,以及时区的下拉列表,如果有人可以帮助清除这一点,我将不胜感激!
发布于 2021-04-21 04:21:13
您只是从本地存储中获取值。但实际上并没有将其分配给任何切换按钮。您需要分配它们才能使其正常工作
function isChecked() {
document.getElementById('checkbox1').checked = localStorage.getItem('checkbox1') === 'true');
}
它是这样工作的:
,
:===检查将为您完成此操作。
https://stackoverflow.com/questions/67185700
复制相似问题