【问题标题】:How can I apply localStorage to input checkbox?如何将 localStorage 应用于输入复选框?
【发布时间】:2020-05-02 06:33:09
【问题描述】:

注意:我只使用 vanilla js。

我目前有一个可以通过select optionslocalStorage 添加/删除类的工作脚本。一切都很好,see jsfiddle here

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

这是我的checkbox's

<input type="checkbox" name="checkbox1" id="checkbox1" onchange="checkbox1(this)">
<input type="checkbox" name="checkbox2" id="checkbox2" onchange="checkbox2(this)">

并在选中/取消选中复选框1时添加/删除类:

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 脚本,适用于我的 select options(完整示例在我的 jsfiddle 中)。如何修改它以使其也适用于我的checkbox's?我假设我必须修改第二行以检查 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'])

})();

【问题讨论】:

  • 是否可以同时选中两个复选框。在那种情况下会发生什么?应该是红色还是蓝色
  • @Ghost 两个复选框的样式不同,它们为不同的元素添加/删除类。所以是的,可以同时检查它们。我已经写了这部分,我想做的是将localStorage 应用到他们身上。刷新后,我希望浏览器记住是否选中了复选框,如果选中则添加类。
  • 在这里。我没有设置颜色,但你可以看到值被保留了。让我知道这是否适合您,以便我可以将其添加为答案jsfiddle.net/qctn08ym/44
  • 您好,我还没有添加课程。您可以在同一个循环中编写函数来添加类。我会更新我的代码
  • 嘿@strawberrymilk 这里是jsfiddle.net/8ufbzrn9/4 课程的链接如果它适合你,请接受答案

标签: javascript input checkbox local-storage


【解决方案1】:

这里是 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;
  })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    相关资源
    最近更新 更多