首页 > 解决方案 > 如何在 localStorage 中存储列表

问题描述

我创建了一个 CRUD 页面,并在用户键入文本时在输入中将文本添加到列表中。现在我想将该列表保存在 localStorage 中,并尝试存储它,但我在控制台日志中得到一个空对象。任何帮助,将不胜感激。

JAVASCRIPT

const addItem = function() {
  let val = input.value;
  if (val) {
    let li = document.createElement('li');
    let inner = '<h1 class="text">' + val + '</h1>';
    inner += '<button class="delete">Delete</button>';
    inner += '<button class="edit">Edit</button>';
    li.innerHTML = inner;
    container.appendChild(li);
    input.value = '';
    currentItem = li.firstChild;  
    //i want to save the below list
    items = document.querySelectorAll('li');
    for(let item of items){
      //this return empty object
      localStorage.setItem('list', JSON.stringify(item) );
      console.log(localStorage)
    }
    for (let del of document.querySelectorAll('.delete')) {
      del.addEventListener('click', deleteItem);
    }
    for (let edit of document.querySelectorAll('.edit')) {
      edit.addEventListener('click', editItem);
    }
  } else {
      alert('please add some text');
    return;
  }
}

如果需要,HTML

<div class="main">
  <h2>JavaScript CRUD Bookmark</h2>
  <form>
    <input type="text" placeholder="search">
  </form>
  <ul></ul>
  <div>
    <input class="add-text" type="text" placeholder="Add Text">
    <button id="add">Add</button>
    <button id="update">update</button>
  </div>
</div>

标签: javascripthtmllocal-storage

解决方案


我已经采用了您的代码并将其重组为您可以完成的解决方案。请阅读我的代码注释以了解我所做的事情。

// HTML is almost the same as yours. I added a class name to the <ul>

// Generates a unique string of characters suitable for a key
function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}

const list = document.querySelector('.current-list'); // the <ul>

const addItem = function() {
  // Get the input value

  let input = document.querySelector('.add-text');
  let val = input.value;

  if (val) {
     // 1. Create unique key
     let uniqueKey = guid();

     // 2. Append item to the list, visually. Note the contentEditable
     //    attribute. We can now click directly into the list item contents
     //    and change it. We can then update the storage when leaving the input.
     list.innerHTML += `\n<li data-key="${uniqueKey}" contentEditable>${val}</li>`;

     // 3. Set the storage key
     localStorage.setItem(uniqueKey, JSON.stringify(val));
  } else {
      alert('please add some text');
    return;
  }
}

// TODO: Add update item function

// TODO: Add delete item function

document
  .querySelector('#add')
  .addEventListener('click', addItem);

小提琴:http: //jsfiddle.net/6mrbaL2n/


推荐阅读