没有从本地存储获取与保存的变量相同的类型

Not getting same type from localStorage as the saved variable had?

本文关键字:保存 变量 类型 获取 存储      更新时间:2023-09-26

我写了一个简单的任务列表。JavaScript代码如下,重要的部分是关于localStorage的。到目前为止,我所做的是这样的:JSBin

我想要实现的是,当我重新加载页面时,是否应立即删除条目的设置(如果是否选中了文本字段旁边的复选框)将从上次访问中保存并恢复。

目前,当我第一次加载页面时,我需要取消选中,然后再次选中复选框,以使其按我想要的方式工作......

这是我的JavaScript/jQuery代码:

var anzahl = 0;
var autoremove = true;
var autoremove_backup = localStorage.getItem("autoremove");
console.log(localStorage.getItem("autoremove"));
$(document).ready(function() {
  if(autoremove_backup===false){
    $("#autoremove").prop( "checked", false);
  }
  else if (autoremove_backup===true){
    $("#autoremove").prop( "checked", true);
  }
  autoremove = autoremove_backup;
  setInterval(entry, 2000);
  $("button").on('click', function() {
    if(this.id=="add"){
      var r = $('<div id="'+ "div"+String(anzahl) +'"><input type="checkbox" id="'+String(anzahl)+'">' + '<label for="'+ String(anzahl)+'" id="'+ "label" +String(anzahl)+'">' + $("#task").val() + '</label><br></div>');
      $("#var").append(r);
      anzahl = anzahl +1;
    }
  });
  $('input[type=checkbox]').change(
    function(){
      if (this.checked) {
        if(String(this.id)==="autoremove"){
          autoremove=true;
          saveAutoremove(autoremove);
        }
      }
      else {
        if(String(this.id)==="autoremove"){
          autoremove=false;
          saveAutoremove(autoremove);
        }
      }
    });
});
function entry(){
if(autoremove===true){
  $('#var input:checked').each(function() {
    $("#div"+String(this.id)).remove();
});
}
}

function saveAutoremove(input){
  localStorage.setItem("autoremove", input);
}

不起作用,因为:

  1. 当任何值存储在localStorage中时,它被强制转换为字符串,因此当您存储基元值truefalse时,它们被强制到字符串'true''false'

  2. 当您从localStorage检索值时,它仍然是一个字符串。

  3. 您的比较使用严格的===比较运算符 将字符串与truefalse进行比较时,结果将始终false。因此,ifelse 子句都不会为真,因此 HTML 中的默认 checked 属性保持不变。请注意,使用非严格==比较不会使代码按预期工作。这是因为字符串'true''false'都强制true。因此,将始终遵循else分支。

您可以通过根据从localStorage返回的字符串值设置autoremove_backup来修复它:

var autoremove_backup = localStorage.getItem("autoremove") === 'true' ? true : false;

我过去使用的另一种方法是使用 JSON.stringifyJSON.parse 序列化/反序列化存储在 localStorage 中的所有内容。

要设置它:

function saveAutoremove(input) {
  localStorage.setItem("autoremove", JSON.stringify(input));
}

要获得它:

var autoremove_backup = JSON.parse(localStorage.getItem("autoremove"));

它增加了一点开销,但它会自动将布尔值转换回布尔值。