我很难弄清楚如何在localStorage中保持切换按钮是或否,即使页面刷新。我还想保持选中或取消选中切换按钮。注意:我也尝试过使用autocomplete="false“,但它不是这样工作的。有人能帮我吗?非常感谢。
HTML
<h1 id="marker" style="text-align: center; padding-bottom:50px;"></h1>
<label class="label-switch switch-primary">
<input type="checkbox" class="switch switch-bootstrap status" name="status" id="status"
onclick="yesno() ">
JS代码
function yesno(){
let status = document.getElementById("status");
if(status.checked == true)
{
localStorage.setItem("isChecked", true);
status.checked = true;
location.reload();
}
if(status.checked == false)
{
localStorage.setItem("isChecked", false);
}
}
marker.innerHTML= localStorage.getItem("isChecked");
发布于 2021-08-14 12:36:42
这是一个包含您正在寻找的解决方案的working sandbox。
我原封不动地保留了标记,但将函数更改为:
function yesno() {
let statusEl = document.getElementById("status");
localStorage.setItem("isChecked",JSON.stringify(statusEl.checked));
const marker = document.getElementById("marker");
marker.innerHTML = localStorage.getItem("isChecked");
}
并添加了以下函数,以便在页面加载时根据需要将复选框标记为选中:
function onInit() {
const isChecked = JSON.parse(localStorage.getItem("isChecked"))
document.getElementById("status").checked = isChecked
}
https://stackoverflow.com/questions/68786538
复制