没有从本地存储获取与保存的变量相同的类型
Not getting same type from localStorage as the saved variable had?
我写了一个简单的任务列表。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);
}
它
不起作用,因为:
当任何值存储在
localStorage
中时,它被强制转换为字符串,因此当您存储基元值true
或false
时,它们被强制到字符串'true'
和'false'
。当您从
localStorage
检索值时,它仍然是一个字符串。您的比较使用严格的
===
比较运算符 将字符串与true
或false
进行比较时,结果将始终false
。因此,if
和else
子句都不会为真,因此 HTML 中的默认checked
属性保持不变。请注意,使用非严格==
比较不会使代码按预期工作。这是因为字符串'true'
和'false'
都强制true
。因此,将始终遵循else
分支。
您可以通过根据从localStorage
返回的字符串值设置autoremove_backup
来修复它:
var autoremove_backup = localStorage.getItem("autoremove") === 'true' ? true : false;
我过去使用的另一种方法是使用 JSON.stringify
和 JSON.parse
序列化/反序列化存储在 localStorage
中的所有内容。
要设置它:
function saveAutoremove(input) {
localStorage.setItem("autoremove", JSON.stringify(input));
}
要获得它:
var autoremove_backup = JSON.parse(localStorage.getItem("autoremove"));
它增加了一点开销,但它会自动将布尔值转换回布尔值。
相关文章:
- 如何将getJson的响应保存在全局变量中
- 为所有查看网站的用户保存变量
- 关闭浏览器后保存变量
- 无法在Node.JS中保存变量
- 在 while 循环中保存变量
- 如何在移动到新的HTML页面后使用保存在Javascript文件中的保存变量
- PHP 会话不通过多个页面保存变量
- 保存变量
- 通过单击图像保存变量
- 在javascript中 - 保存变量作为参考
- 使用JavaScript onclick删除元素,并在SQL中保存变量
- 在cookie中保存变量- console.log返回具有会话id的变量
- JavaScript:在调用之间保存变量的值
- 如何在hta中保存变量,以便在关闭和打开hta后保存
- 在闭包中保存变量内容有问题
- 当html页面发生变化时,如何保存变量的状态
- 在闭包范围中保存变量
- Javascript 在使用 XMLHttpRequest 时通过作用域保存变量
- 在 cookie 中查找并保存变量
- 保存变量的值