【问题标题】:Not getting same type from localStorage as the saved variable had?没有从 localStorage 获得与保存的变量相同的类型?
【发布时间】:2016-08-17 02:50:11
【问题描述】:

我写了一个简单的任务列表。 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);
}

【问题讨论】:

  • 一切都以 string 的形式存储在 localStorage.
  • 啊,谢谢,我还以为是类型问题...
  • 当将某些内容连接到字符串文字时,不必显式地将其转换为字符串,它将被隐式转换。你可以写"#div" + this.id 而不是"#div" + String(this.id)。有时您可能只是为了清楚起见而想要明确,但是当文字在左侧时,它应该是不言而喻的。

标签: javascript jquery checkbox local-storage


【解决方案1】:

它不起作用,因为:

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

  2. 当将字符串与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"));

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

【讨论】:

  • JSON 方法也适用于几乎任何东西。它允许您存储对象或数组,只要它们的属性/元素可以由 stringify 存储(即所有属性都是可枚举的,不包含函数等)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-29
  • 1970-01-01
  • 2019-11-03
  • 2020-02-23
  • 2011-07-21
  • 2018-10-01
相关资源
最近更新 更多