简体   繁体   中英

How to get multiple items in localstorage

I am using local storage to set todo items.

But I am somewhat new to JavaScript, so I am really confused about this matter. I know how to set local storage items though. Anyway, I know that I need to use a list to do this, but I'm confused to do that too.

Please show me how to do that in code (add localstorage items to list and create

tags with innerHTML of the list values). Here is my current code.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag -->
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <div id='shopping-list' class="shopping-list">
      <h1>Todo List</h1>
      <input placeholder="Add todo and press enter to submit" id="todo" />
      <li>Learn JavaScript</li>
      <li>Study Neural Networks</li>
      <li>Learn Python</li>
    </div>
  </body>
  <script src="main.js"></script>
  <script>
    todo = document.getElementById("todo")
    todo.addEventListener('keyup', function (e) {
      if (e.key === 'Enter' || e.keyCode === 13) {
        let todo = document.getElementById("todo");
        if (!todo.value) {
          todo.style.borderColor = 'red';
          todo.style.boxShadow = '0px 0px 5px red';
        } else {
            var li = document.createElement('li');
            localStorage.setItem('todo_val', todo.value)
            var todo_value = localStorage.getItem('todo_val')
            var node = document.createTextNode(todo_value);
            li.appendChild(node);
            var place = document.getElementById('shopping-list');
            place.appendChild(li);
            todo.style.borderColor = 'black';
            todo.style.boxShadow = '0px 0px 5px white';
        }
      }
    });
    let todo_val = localStorage.getItem('todo_val')
    console.log(todo_val)
    var li = document.createElement('li');
    var node = document.createTextNode(todo_value);
    li.appendChild(node);
    var place = document.getElementById('shopping-list');
    place.appendChild(li);
  </script>
</html>

Thank you.

LocalStorage allows you to store strings. To store an array you can serialize it (turn it into a string). A common way of serializing is JSON.stringify() , unserialize with JSON.parse() .

const array = [ "a", "b" ];
const serializedArray = JSON.stringify(array); // '["a","b"]'
const arrayAgain = JSON.parse(serializedArray ); // [ "a", "b" ]

Keep in mind that in theory the user can modify what is in the localstorage, so be robust against 'bad data'. Maybe the data is corrupt (reset to default state?) or maybe the user added stuff, so for instance don't store permissions in localstorage. A common way of describing this is to say that you should treat everything in the localstorage as 'user input'.

You can use an array and set-get it using JSON.parse/JSON.stringify.

// Prevent code duplicataion
function addTodoLi(place, todoValue) {
  var li = document.createElement('li');
  var node = document.createTextNode(todoValue);
  li.appendChild(node);
  place.appendChild(li);
}

todo = document.getElementById("todo")

todo.addEventListener('keyup', function (e) {
  if (e.key === 'Enter' || e.keyCode === 13) {
    let todo = document.getElementById("todo");
    if (!todo.value) {
      todo.style.borderColor = 'red';
      todo.style.boxShadow = '0px 0px 5px red';
    } else {
        var place = document.getElementById('shopping-list');
        addTodoLi(place, todo.value)
        todos.push(todo.value)
        localStorage.setItem('todos', JSON.stringify(todos)) // You can only store string
        todo.style.borderColor = 'black';
        todo.style.boxShadow = '0px 0px 5px white';
    }
  }
});

let todos = localStorage.getItem('todos')
todos = todos ? JSON.parse(todos) : [] // todos may be undefined

var place = document.getElementById('shopping-list');
todos.forEach(todo => {
  addTodoLi(place, todo)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM