📌  相关文章
📜  如何防止刷新页面后待办事项消失 - javascript代码示例

📅  最后修改于: 2022-03-11 15:03:42.087000             🧑  作者: Mango

代码示例1
const addButton = document.querySelector("#addToDo");
const delBtn = document.querySelector("#delToDo");

addButton.addEventListener("click", addTask, false);
var tasksID = 0;

function saveTask(taskID, taskInfo) {
  // Get tasks from local storage
  let tasks = localStorage.getItem("todo-tasks");

  if (!tasks) {
    tasks = {};
  } else {
    tasks = JSON.parse(tasks);
    tasks[taskID] = taskInfo;
  }

  // Save the result back
  let infobj = JSON.stringify(tasks);
  localStorage.setItem("todo-tasks", infobj);
}

function drawSavedTasks() {
  let tasks = localStorage.getItem("todo-tasks");
  if (tasks) {
    tasks = JSON.parse(tasks);
    Object.keys(tasks).forEach(k => {
      addTask(null, tasks[k]);
    });
  }
}

drawSavedTasks();

function addTask(e, textToDo = undefined) {
  if (!textToDo) {
    textToDo = document.querySelector("#toDo").value;
  }

  var list = document.querySelector(".list");
  var divToDo = document.createElement("div");
  var p = document.createElement("p");
  var delButton = document.createElement("button");

  divToDo.setAttribute("id", "todo" + tasksID);
  divToDo.setAttribute("class", "toDo");
  delButton.classList.add("delToDo");

  delButton.textContent = "Delete";
  p.textContent = textToDo;

  delButton.onclick = function() {
    divToDo.parentNode.removeChild(divToDo);
  }

  divToDo.appendChild(p);
  divToDo.appendChild(delButton);

  list.appendChild(divToDo);
  saveTask(tasksID, textToDo);
  ++tasksID;
}