javascript - localStorage 无法在 JavaScript 中运行

标签 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>

最佳答案

您的代码似乎确实有效。如果您在 loadFromLocalStorage 函数中第 49 行上方的 console.log(JSON.parse(localStorageItems)) 中,它会按预期在控制台中显示。此外,刷新后这些项目仍然存在。

如果您的意思是您正在检查 localStorage,但没有看到这些项目,则可能是您正在查看 localStorage 的预览版本。 (我假设您使用的是 Chrome。)将鼠标悬停在空白部分的顶部并下拉,这应该会显示存储的值。如果您单击其中一个,它应该显示在预览部分中。我认为这是最近实现的 Chrome 开发工具 UI 更改。

enter image description here

enter image description here

关于javascript - localStorage 无法在 JavaScript 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52246671/

相关文章:

javascript - 当记录超过一个时,无法禁用文本字段

javascript - ng-repeat 内部的 Angular 下拉菜单,具有所选选项所需的附加逻辑

javascript - 是否可以使用 Spring-WebSockets 通过 WebSockets 通过 STOMP 发送二进制数据?

javascript - 自定义下拉列表不起作用

javascript - jQuery - 设置附加数量限制

javascript - 使用 javascript 获取 UTC 时间(以秒为单位)

javascript - icheck.js 和 Meteor 应用程序

javascript - Jquery resizing() 显示调整大小图标但不调整大小

javascript - 将 jquery 变量赋值给 php 变量

javascript - 使用 php 将 append javascript 中的值 POST 提交到 mysql