首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >localStorage在JavaScript中不起作用

localStorage在JavaScript中不起作用
EN

Stack Overflow用户
提问于 2018-09-10 00:49:10
回答 2查看 56关注 0票数 0

我正在尝试用纯JavaScript (没有额外的框架或库)创建一个单页面应用程序。问题是我添加到TODO列表中的值没有存储在localStorage中(并且没有显示)。

如果能帮助我完成这项任务,我将不胜感激。

如何简化代码?(不使用任何额外的库和框架(ex.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>

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-09-10 01:18:28

您的代码看起来确实可以工作。如果您在loadFromLocalStorage函数的第49行上方使用console.log(JSON.parse(localStorageItems))命令,它将在控制台中按预期显示。此外,在刷新时,这些项将持续存在。

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

票数 1
EN

Stack Overflow用户

发布于 2018-09-10 01:07:19

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52246671

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档