注意:我只使用 vanilla js。
我目前有一个工作脚本,可以通过选择选项
以及localStorage
添加/删除类。一切都很好,see jsfiddle here .
现在,我想添加两个复选框
以相同的方式执行。我的问题是我不确定如何将复选框添加到我当前的 localStorage 脚本中。
这是我的复选框
:
<input type="checkbox" name="checkbox1" id="checkbox1" onchange="checkbox1(this)">
<input type="checkbox" name="checkbox2" id="checkbox2" onchange="checkbox2(this)">
并在选中/取消选中 checkbox1 时添加/删除类:
var checkbox = document.getElementById('checkbox1');
checkbox.addEventListener("change", checkbox1, false);
function checkbox1() {
var isChecked = checkbox.checked;
if (isChecked) {
[].map.call(document.querySelectorAll('body,.nc,.tags'), function(el) {
el.classList.add('classname');
});
} else {
[].map.call(document.querySelectorAll('body,.nc,.tags'), function(el) {
el.classList.remove('classname');
});
}
}
工作正常。现在我只需要将其添加到 localStorage
中。
这是我的 localStorage
脚本,适用于我的选择选项
(完整示例在我的 jsfiddle 中)。如何修改它以使其也适用于我的复选框
?我假设我必须修改第二行来检查 checkbox
而不是 options
但我不确定如何操作。
function selectTest(element) {
const a = element.options[element.selectedIndex].value;
setTest(a);
localStorage['test'] = a;
}
function setTest(a) {
if (a == "option1") {
//add+remove classes here
}
}
(function() {
if (localStorage['test'])
document.getElementById("test").value = localStorage['test'];
setTest(localStorage['test'])
})();
最佳答案
如果你只是想直接查看代码,这里是 JS Fiddle https://jsfiddle.net/qctn08ym/44/
这个想法是,由于可以勾选多个复选框,并且我们需要保留它,因此我们可以将其存储为数组。请注意,您只能在 localStorage 中存储字符串,因此您需要将数组转换为字符串,反之亦然。
在更改任何复选框值时,我们可以调用下面的函数来设置本地存储
function checkboxChanged(e) {
//Get the id of all checked checkboxes and store them as array
// You can do this in loop as well by setting common class on checkboxes
var c = []
if(document.getElementById('checkbox1').checked) {
c.push('checkbox1');
}
if(document.getElementById('checkbox2').checked) {
c.push('checkbox2');
}
localStorage['test'] = c.toString();
}
然后您可以在文档加载时调用下面的函数
function checkOnLocalStorage() {
if(!localStorage['test']) return;
var checked = localStorage['test'].split(',');
checked.map((id) => {
document.getElementById(id).checked=true;
})
}
关于javascript - 如何将 localStorage 应用于输入复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61555401/