【发布时间】: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