Demo JS-Localstorage - ToDoList- Demo
Localstorage side project 簡單說明一下這個side project:
輸入內容
點擊加入待辦事項
下方依照順序列出待辦事項,並可以點擊刪除 如下圖:
1 2 3 <input type ="text" class ="textClass" placeholder ="請填寫代辦內容" /> <input type ="button" class ="addList" value ="加入代辦" /> <ul class ="list" > </ul >
要特別注意幾點
一開始要給待辦事項清單一個空陣列
一開始就需要更新一次清單
儲存與刪除清單時都要先將陣列轉為字串再setItem進localstorage
待辦事項清單在新增或刪除後已經是以字串的方式儲存,要調用的時候要先轉回原本陣列型別
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 var list = document .querySelector(".list" );var addList = document .querySelector(".addList" );var data = JSON .parse(localStorage.getItem("toDoList" )) || [];addList.addEventListener("click" , saveItem); list.addEventListener("click" , deleteItem); updateList(data); function saveItem (e ) { e.preventDefault(); var str = document .querySelector(".textClass" ).value; var todo = { content: str }; data.push(todo); updateList(data); localStorage.setItem("toDoList" , JSON .stringify(data)); } function updateList (items ) { str = "" ; var len = items.length; for (var i = 0 ; i < len; i++) { str += '<li><a href="#" data-index=' + i + ">刪除</a> <span>" + items[i].content + "</span></li>" ; } list.innerHTML = str; } function deleteItem (e ) { e.preventDefault(); if (e.target.nodeName !== "A" ) { return ; } var index = e.target.dataset.index; data.splice(index, 1 ); localStorage.setItem("toDoList" , JSON .stringify(data)); updateList(data); }