localStorage在JavaScript中不起作用

时间:2018-09-09 16:49:10

标签: javascript

我正在尝试使用纯JavaScript(没有其他框架或库)制作单页应用程序。问题是我添加到TODO列表中的值未存储在localStorage中(并且未显示)。

在此任务上的任何帮助,我将不胜感激。

如何简化代码? (不使用任何其他库和框架(例如jQuery等))

这是我的代码:

let inputTask = document.getElementById('toDoEl');
let editTask = document.getElementById('editTask');
let checkTask = document.getElementById('list');
let emptyList = document.getElementById('emptyList');

let items = [];
let id = [];
let labelToEdit = null;
const empty = 0;

let pages = ['index', 'add', 'modify'];

load();

function load() {
  items = loadFromLocalStorage();
  id = getNextId();

  items.forEach(item => renderItem(item));
}

function show(shown) {
  location.href = '#' + shown;
  pages.forEach(function(page) {
    document.getElementById(page).style.display = 'none';
  });
  document.getElementById(shown).style.display = 'block';
  return false;
}

function getNextId() {

  for (let i = 0; i<items.length; i++) {
    let item = items[i];
    if (item.id > id) {
      id = item.id;
    }
  }
  id++;
  return id;
}

function loadFromLocalStorage() {
  let localStorageItems = localStorage.getItem('items');

  if (localStorageItems === null) {
    return [];
  }

  return JSON.parse(localStorageItems);
}

function saveToLocalStorage() {
  localStorage.setItem('items', JSON.stringify(items));
}

function setChecked(checkbox, isDone) {
  if (isDone) {
    checkbox.classList.add('checked');
    checkbox.src = 'https://image.ibb.co/b1WeN9/done_s.png';
    
    let newPosition = checkTask.childElementCount - 1;
    let listItem = checkbox.parentNode;
    listItem.classList.add('checked');
    checkTask.removeChild(listItem);
    checkTask.appendChild(listItem);
  } else {
    checkbox.classList.remove('checked');
    checkbox.src = 'https://image.ibb.co/nqRqUp/todo_s.png';
    let listItem = checkbox.parentNode;
    listItem.classList.remove('checked');
  }
}

function renderItem(item) {
  let listItem = document.getElementById('item_template').cloneNode(true);
  listItem.style.display = 'block';
  listItem.setAttribute('data-id', item.id);

  let label = listItem.querySelector('label');
  label.innerText = item.description;

  let checkbox = listItem.querySelector('input');

  checkTask.appendChild(listItem);

  setChecked(checkbox, item.isDone);

  emptyList.style.display = 'none';

  return listItem;
}

function createNewElement(task, isDone) {

  let item = { isDone, id: id++, description: task };
  items.push(item);

  saveToLocalStorage();

  renderItem(item);
}

function addTask() {  
  if (inputTask.value) {
    createNewElement(inputTask.value, false);
    
    inputTask.value = '';

    show('index');
  }
}

function modifyTask() {  
  if (editTask.value) {

    let item = findItem(labelToEdit);
    item.description = editTask.value;
    labelToEdit.innerText = editTask.value;
    saveToLocalStorage();
   
    show('index');
  }
}

function findItem(child) {
  let listItem = child.parentNode;

  let id = listItem.getAttribute('data-id');
  id = parseInt(id);
  let item = items.find(item => item.id === id);

  return item;
}

// Chanhe img to checked
function modifyItem(label) {

  labelToEdit = label;
  editTask.value = label.innerText;

  show('modify');

  editTask.focus();
  editTask.select();
}

function checkItem(checkbox) {
  let item = findItem(checkbox);

  if (item === null) {
    return;
  }
  item.isDone = !item.isDone;

  saveToLocalStorage();

  setChecked(checkbox, item.isDone);
}

function deleteItem(input) {
  let listItem = input.parentNode;

  let id = listItem.getAttribute('data-id');
  id= parseInt(id);
  for (let i in items) {
    if (items[i].id === id) {
      items.splice(i, 1);
      break;
    }
  }

  if (items.length === empty) {
    emptyList.style.display = 'block';
  }

  saveToLocalStorage();

  listItem.parentNode.removeChild(listItem);
}
* {
  box-sizing: border-box;
}
body {
  font-family: sans-serif;
}
h2, li, #notification {
  text-align: center;
}
h2 {
  font-weight: normal;
  margin: 0 auto;
  padding-top: 20px;
  padding-bottom: 20px;
}
#root {
  width: 400px; 
  height: 550px;
  margin: 0 auto;
  position: relative;
}
#root>ul {
  display: block;
}
#addButton {
  display: block;
  margin: 0 auto;
}
.checkbox, .delete { 
  height: 24px;
  bottom: 0; 
}
.checkbox {
  float: left;
}
.delete {
  float: right;
}
ul {
  margin: 20px 30px 0 30px;
  padding-top: 20px;
  padding-left: 20px;
  text-align: center;
}

#toDoEl {
  width: 50%;
}
li {
  width: 100%;
  list-style: none;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 15px auto;
}
label {
  margin: 0 auto;
  text-align: justify;
  text-justify: inter-word;
}
label:hover {
  cursor: auto;
}
li.checked { 
  background-color: gray;
}
span.button {
    cursor: pointer;
}
#add, #modify {
  display: none;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Homework 12 - Simple TODO List</title>
  <link rel="stylesheet" href="./assets/styles.css">
</head>

<body>
  <div id="root">
    <!--Main page-->
    <div id="index">
      <h2>Simple TODO Application</h2> 
      <button class="button" id="addButton" onclick="show('add')">Add New Task</button>
      <p id="emptyList">TODO is empty</p>
      <ul id="list">
        <li id="item_template" style="display: none">
          <input class="checkbox" type="image" alt="checkbox" src="https://image.ibb.co/nqRqUp/todo_s.png" onclick="checkItem(this)">
          <label onclick="modifyItem(this)"></label>
          <input id="delete" class="delete" type="image" alt="remove" src="https://image.ibb.co/dpmqUp/remove_s.jpg" onclick="deleteItem(this)">
        </li>
      </ul>
    </div>
    <!--Add page-->
    <div id="add">
      <h2>Add Task</h2>
      <input type="text" id="toDoEl">
      <button class="button cancel" onclick="show('index')">Cancel</button>
      <button class="button save" onclick="addTask()">Save changes</button>
    </div>
    <!--Modify page-->
    <div id="modify">
      <h2>Modify item</h2>
      <input type="text" id="editTask">
      <button class="button cancel" onclick="show('index')">Cancel</button>
      <button class="button save" onclick="modifyTask()">Save changes</button>
    </div>
  </div>

  <script src="./src/app.js"></script>
</body>

</html>

2 个答案:

答案 0 :(得分:1)

我在Codepen中检查了您的代码,它可以正常工作。

enter image description here

答案 1 :(得分:1)

您的代码确实起作用了。如果您在console.log(JSON.parse(localStorageItems))函数中的第49行上方loadFromLocalStorage,它将在控制台中按预期显示。同样,在刷新时,这些项目仍然存在。

如果您的意思是正在检查localStorage而没有看到这些项目,则可能是您正在查看localStorage的预览版。 (我假设您使用的是Chrome。)将鼠标悬停在空白部分的顶部,然后向下拉,这将显示存储的值。如果单击一个,它将显示在预览部分。我认为这是最近实施的Chrome开发者工具用户界面更改。

enter image description here

enter image description here