Javascript 如何将localStorage应用于输入复选框?

Javascript 如何将localStorage应用于输入复选框?,javascript,input,checkbox,local-storage,Javascript,Input,Checkbox,Local Storage,注意:我只使用香草js 我目前有一个工作脚本,可以通过select选项和localStorage添加/删除类。一切都很好 现在,我想添加两个复选框,以同样的方式执行。我的问题是我不确定如何将复选框添加到当前的localStorage脚本中 以下是我的复选框: 很好。现在我只需要将它添加到localStorage 下面是我的本地存储脚本,它适用于我的JSFIDLE中的select options完整示例。我如何修改它以使其也适用于我的复选框?我假设我必须修改第二行以检查复选框而不是选项,但我不确定

注意:我只使用香草js

我目前有一个工作脚本,可以通过select选项和localStorage添加/删除类。一切都很好

现在,我想添加两个复选框,以同样的方式执行。我的问题是我不确定如何将复选框添加到当前的localStorage脚本中

以下是我的复选框:

很好。现在我只需要将它添加到localStorage

下面是我的本地存储脚本,它适用于我的JSFIDLE中的select 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提琴

其思想是,由于可以勾选多个复选框,我们需要保留它们,因此我们可以将其存储为一个数组。请注意,您只能在localStorage中存储字符串,因此需要将数组转换为字符串,反之亦然

对于任何更改的复选框值,我们可以调用下面的函数来设置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;
  })
}

可以同时选中这两个复选框。在那种情况下会发生什么?应该是红色还是红色blue@Ghost这两个复选框都设置了不同的样式,它们向不同的元素添加/删除类。是的,它们可以同时被检查。我已经写了这一部分,我正在尝试对它们应用本地存储。刷新后,我希望浏览器记住是否选中了复选框,如果选中,则添加类。我没有设置颜色,但您可以看到值被保留。让我知道这是否对你有效,这样我就可以添加它作为回答嗨,我还没有添加类。您可以在同一个循环中编写函数来添加类。我会更新我的代码Hey@strawberrymilk这里是与课程的链接如果对你有效,请接受答案
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;
  })
}