LocalStroage上手:实现一个刷新后仍然存在的ToDoList

LocalStroage、SessionStroage、Cookie之间的区别、功能、优劣势就不提了,网上的博客一个比一个详细,这个demo的实现也很简单,在这里就直接上这个demo的源码

(不得不说这个作者的代码写的真的有种美感,这个demo来自知乎专栏 我是前端切图仔

 <!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <meta http-equiv="X-UA-Compatible" content="ie=edge">
     <title>Document</title>
 </head>
 <style>
     html {
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

.wrapper {
    padding: 20px;
    max-width: 350px;
    background: rgba(228, 215, 215, 0.95);
    box-shadow: 0 0 0 5px rgba(187, 157, 157, 0.5);
}
h2 {
    text-align: center;
    margin: 0;
    font-weight: 200;
}
.plates {
    margin: 0;
    padding: 0;
    text-align: left;
    list-style: none;
}
.plates li {
  border-bottom: 1px solid rgba(0,0,0,0.2);
  padding: 10px 0;
  font-weight: 100;
  display: flex;
}
.plates label {
  flex:1;
  cursor: pointer;
}
.plates input {
  display: none;
}
.plates input + label:before {
  content: '⬜️';
  margin-right: 10px;
}
.plates input:checked + label:before {
  content: '☆';
}
.add-items {
  margin-top: 20px;
}
.add-items input {
  padding:10px;
  outline:0;
  border:1px solid rgba(0,0,0,0.1);
}
.add-items input:nth-child(1){
  width: 61.3%;
}
.add-items input:nth-child(2) {
  width: 30%;
  color: rgb(85, 108, 128);
  font-weight: 700;
}
.buttons button {
  width: 100px;
  margin-top: 10px;
  height: 40px;
  color: rgb(85, 108, 128);
  font-weight: 700;
  border:1px solid rgba(0,0,0,0.1);
}
 </style>
 <body>
    <div class="wrapper">
        <h2>ToooooDo</h2>
        <p></p>
        <ul class="plates">
          <li>待添加事项</li>
        </ul>
        <form class="add-items">
          <input type="text" name="item" placeholder="Item Name" required>
          <input type="submit" value="添   加">
        </form>
        <div class="buttons">
            <button data-action="clear">删除所有</button>
            <button data-action="check">全部选中</button>
            <button data-action="uncheck">取消全选</button>
        </div>
    </div>
</body>
<script>
  // var str = '{"name":"harold"}';
  // var obj = {
  //   name:'harold'
  // }
  // console.log(JSON.parse(str),JSON.stringify(obj));
(function(){
    function newFun(){
      var addItems = document.querySelector('.add-items'),
          itemsList = document.querySelector('.plates'),
          buttons = document.querySelector('.buttons'),
          items = JSON.parse(localStorage.getItem('items')) || [];

      //添加item的处理函数
      function handleAdd(e){
        console.log(e);//type=submit
        e.preventDefault();
        console.log(this);//猜想应该是整个表单控件
        var name = this.querySelector('[name=item]').value;

        var item = {
          name:name,
          done:false
        };
        items.push(item);
        localStorage.setItem('items',JSON.stringify(items));
        updateList(items,itemsList);
        this.reset();
      }

      function updateList(plates = [],plateList){
        console.log(arguments);
        plateList.innerHTML = plates.map(function(plate,i){
          return ' <li><input type="checkbox" data-index=" ' + i + '" id="plate' + i + '" ' + (plate.done ? 'checked' : '')
          + ' /><label for="plate' + i + '">' + plate.name + '</label></li>';
        }).join('');
      }
      //委托input(typecheckbox)列表的父元素进行监听
   function toggleChecked(e){
     if(!e.target.matches('input')) return;//如果没有子元素则中止执行
     var item = e.target.dataset.index;
     items[item].done = !items[item].done;//更改状态
     localStorage.setItem('items',JSON.stringify(items));
     updateList(items,itemsList);
   }

   //添加button事件
   function doButtonPress(e){
     var action = e.target.dataset.action;
     switch(action){
       case"clear":
        items = [];
        break;
      case"check":
        items.map(function(item){
          return item.done = true;
        });
        break;
      case"uncheck":
        items.map(function(item){
          return item.done = false;
        });
        break;
      default:
        return;
     }

     localStorage.setItem('items',JSON.stringify(items));
     updateList(items,itemsList)
   }
   addItems.addEventListener('submit',handleAdd);
   itemsList.addEventListener('click',toggleChecked);
   buttons.addEventListener('click',doButtonPress);

   updateList(items,itemsList);
}
    document.addEventListener('DOMContentLoaded',newFun);
}());
</script>

 </html>
原文地址:https://www.cnblogs.com/linbudu/p/11031182.html