Как сохранить данные в локальном хранилище - PullRequest
1 голос
/ 10 июля 2020

Я создаю список дел в javascript, и все было хорошо, пока мне не пришлось иметь дело с локальным хранилищем. Я хочу иметь возможность обновлять sh страницу без потери того, что я поместил в свой список только что.

Я искал на многих форумах, но не нашел похожего случая.

Вот часть моего HTML кода: Просто ul и ввод

Вот часть моего JS кода: Моя функция, которая создает li внутри моего ul

И вот предварительный просмотр моего списка дел: Надеюсь, это поможет

Так что, если я недостаточно хорошо объяснил свою проблему, позвольте мне знаю, и я внесу больше уточнений.

Спасибо за чтение!

PS: Я должен указать, что я уже читал документацию на MDN и других веб-сайтах, и я понял принцип localStorage, но я ' m борется с интеграцией этого в свой код. Я видел много примеров его использования, но они часто слишком просты или наоборот слишком разные / трудны для понимания. Вот почему я прошу вашей помощи, чтобы получить более личный ответ.

window.addEventListener('load', function()
{
    var yourToDo = document.getElementById('myInput');
    yourToDo.addEventListener('keydown', myFunction);
    function myFunction(e)
    {
        if (e.keyCode == 13)
        {
            var line = document.createElement('div'); //This is my div which contains the 3 items which constitute a line
            line.classList.add('myLine');
            document.getElementById('myUl').appendChild(line);

            var circle = document.createElement('i'); //The first item is a circle which can be check or unchecked
            circle.id = 'myCircle';
            document.querySelector('.myLine:last-child').appendChild(circle);
            circle.addEventListener('click', function()
            {
                this.classList.toggle('fas');
                this.classList.toggle('fa-check-circle');
                this.classList.toggle('unstyled');
                task.classList.toggle('crossedOut')
            });

            var task = document.createElement('li'); //The second item is a <li> which contains the value of the input
            task.innerHTML = yourToDo.value.charAt(0).toUpperCase() + yourToDo.value.slice(1);
            document.querySelector('.myLine:last-child').appendChild(task);         
            
            var trash = document.createElement('i'); //The third item is a trash which suppresses the whole line
            trash.classList.add('fas');
            trash.classList.add('fa-trash-alt');
            document.querySelector('.myLine:last-child').appendChild(trash);
            trash.addEventListener('click', function()
            {
                this.parentNode.remove();
            });

            yourToDo.value = '';
        }
    }
<section>
                <ul id="myUl"></ul>
                <label>
                    <input id="myInput" type="text" placeholder="Add your to do task" onfocus="this.placeholder = ''"    onblur="this.placeholder = 'Add your to do task'">
                </label>
            </section>

1 Ответ

0 голосов
/ 10 июля 2020

Я не думаю, что localStorage работает в фрагментах кода, но попробуйте это в своем собственном коде.

Я добавил в ваш код функцию, которая получает все элементы localStorage и создает элемент списка для каждого из них. загрузка страницы. Также добавлено место, где вы должны сохранить его в localStorage в исходной функции.

Комментарии добавляются повсюду.

Надеюсь, это поможет

window.addEventListener('load', function() {
  var yourToDo = document.getElementById('myInput');
  yourToDo.addEventListener('keydown', myFunction);

  function myFunction(e) {
    if (e.keyCode == 13) {
      var line = document.createElement('div'); //This is my div which contains the 3 items which constitute a line
      line.classList.add('myLine');
      document.getElementById('myUl').appendChild(line);

      var circle = document.createElement('i'); //The first item is a circle which can be check or unchecked
      circle.id = 'myCircle';
      document.querySelector('.myLine:last-child').appendChild(circle);
      circle.addEventListener('click', function() {
        this.classList.toggle('fas');
        this.classList.toggle('fa-check-circle');
        this.classList.toggle('unstyled');
        task.classList.toggle('crossedOut')
      });

      var task = document.createElement('li'); //The second item is a <li> which contains the value of the input


      task.innerHTML = yourToDo.value.charAt(0).toUpperCase() + yourToDo.value.slice(1);

      //Set loacl storage item
      localStorage.setItem(yourToDo.value.charAt(0).toUpperCase() + yourToDo.value.slice(1), yourToDo.value.charAt(0).toUpperCase() + yourToDo.value.slice(1));

      document.querySelector('.myLine:last-child').appendChild(task);

      var trash = document.createElement('i'); //The third item is a trash which suppresses the whole line
      trash.classList.add('fas');
      trash.classList.add('fa-trash-alt');
      document.querySelector('.myLine:last-child').appendChild(trash);
      trash.addEventListener('click', function() {
        this.parentNode.remove();
      });

      yourToDo.value = '';
    }
  }
});


function load() {

  //Create each item (as you did above)
  function create(item) {
    var yourToDo = document.getElementById('myInput');

    var line = document.createElement('div'); //This is my div which contains the 3 items which constitute a line
    line.classList.add('myLine');
    document.getElementById('myUl').appendChild(line);

    var circle = document.createElement('i'); //The first item is a circle which can be check or unchecked
    circle.id = 'myCircle';
    document.querySelector('.myLine:last-child').appendChild(circle);
    circle.addEventListener('click', function() {
      this.classList.toggle('fas');
      this.classList.toggle('fa-check-circle');
      this.classList.toggle('unstyled');
      task.classList.toggle('crossedOut')
    });

    var task = document.createElement('li'); //The second item is a <li> which contains the value of the input

    //Set innerHTML to item that you ar passing in for loop below
    task.innerHTML = item;
    document.querySelector('.myLine:last-child').appendChild(task);

    var trash = document.createElement('i'); //The third item is a trash which suppresses the whole line
    trash.classList.add('fas');
    trash.classList.add('fa-trash-alt');
    document.querySelector('.myLine:last-child').appendChild(trash);
    trash.addEventListener('click', function() {
      this.parentNode.remove();
    });

    yourToDo.value = '';
  }


  //Create an array to store all local storage items
  var values = [],
    keys = Object.keys(localStorage),
    a = keys.length;

  //Push items to array
  while (a--) {
    values.push(localStorage.getItem(keys[a]));
  }

  //Create a for loop and loop through all array items and pass each item value to the create funtion above
  for (let i = 0; i < Object.keys(localStorage).length; i++) {
    create(values[i])
  }
}
//Call load on page load up (it would actually be better if you add this in your window "load" listener above )
load();


//Hope this helps!
<section>
  <ul id="myUl"></ul>
  <label>
    <input id="myInput" type="text" placeholder="Add your to do task" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Add your to do task'">
  </label>
</section>
...