我正在创建一个看板,被困于从本地存储中删除对象。我有3个看板列的3个数组,它们用不同的键存储。我需要单击删除某些卡,然后更新本地存储中的阵列。
我已经可以恢复项目并在单击时删除标记,但是它仍在本地存储中。 这是我的工作代码:
var saveToStorage = function (data, key) {
var dataString = JSON.stringify(data);
localStorage.setItem(key, dataString);
};
var getFromStorage = function (key) {
var dataString = localStorage.getItem(key);
return JSON.parse(dataString);
};
var deleteFromList = function (task, list) {
for (var i in list) {
var currentTask = list[i];
if (tasksAreEqual(currentTask, task)){
list.splice(i, 1);
}
}
};
var tasksAreEqual = function (task1, task2) {
var task1Str = JSON.stringify(task1);
var task2Str = JSON.stringify(task2);
return task1Str === task2Str;
};
var createCard = function (task) {
var card = $("<div class = \"card\">");
var cardBody = $("<div class=\"card-body\">");
var cardHeader = $("<div class=\"d-flex justify-content-between align-items-start\">");
var cardText = $("<p class=\"card-text\">").text(task.message);
var btnRemove = $("<button type='button' id='remove' class='btn btn-outline-danger'>").text("x");
var btnNext = $("<button type='button' id='next' class='btn btn-outline-success'>").text("Next =>");
cardHeader.append(cardText, btnRemove);
cardBody.append(cardHeader, btnNext);
card.append(cardBody)
btnRemove.on("click", function(e) {
e.preventDefault();
card.remove();
});
$("#todo").append(card);
};
var todoList = getFromStorage("todo") || [];
var progressList = getFromStorage("progress") || [];
var doneList = getFromStorage("done") || [];
var btnAdd = $("#add-btn");
btnAdd.on("click", function () {
var taskMsg = $("#task-msg").val();
var task = {
message: taskMsg
};
createCard(task);
todoList.push(task);
saveToStorage(todoList, "todo");
});
$(function() {
var todoArr = getFromStorage("todo");
for (var i of todoArr) {
var task = i;
createCard(task);
}
});
答案 0 :(得分:0)
删除任务后将列表保存到localStorage
// added "return list;"
var deleteFromList = function(task, list) {
for (var i in list) {
if (tasksAreEqual(list[i], task)) {
list.splice(i, 1);
}
}
return list;
};
btnRemove.on("click", function(e) {
e.preventDefault();
todoList = deleteFromList(task, todoList);
localStorage.setItem('todo', JSON.stringify(todoList))
card.remove();
});
$(function() {
var todoArr = getFromStorage("todo");
// prevent the error 'TypeError: todoArr is null'
if (!todoArr) return;
for (var i of todoArr) {
var task = i;
createCard(task);
}
});