iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 22
2
Modern Web

實作經典 JavaScript 30系列 第 22

Day22: LocalStorage(二)

我們就必須使用LocalStorage
來讓瀏覽器記住剛才輸入的資料
紀錄完成後,同時將表單的回復成未輸入的狀態

localStorage.setItem('items', JSON.stringify(items));
this.reset();

加上localStorage.setItem(),可以按下F12觀察
Application中的LocalStorge,
這時可以試著新增待辦事項
假如我輸入了aaa 、 bbb
那麼localStorage都會幫我記錄起來

確定資料都被記錄起來後
原本的items變數設定就可以改變成
由LocalStorage取得資料

const items = JSON.parse(localStorage.getItem('items')) || [];

3.利用LocalStorage,保留已完成的狀態
接下來別忘了已完成的狀態也需要保留,
所以這個狀態也要寫入localstorage中
一樣設置監聽器,並寫上簡單的函式
我們現在要監聽整張todoList,
出現click事件就觸發toggleDone函式

function toggleDone(e) {
  console.log(e.target) 
  console.log(e.currentTarget) 
}

//監聽器
itemsList.addEventListener('click', toggleDone);

e.target
會顯示當前點擊的位置,
所以有可能是<input>,也有可能是<li>
我們想要針對input的位置來抓取
所以改寫函式

function toggleDone(e) {
    if (!e.target.matches('input')) return; 
    //如果不是input,就不執行下方的動作
}

排除其他的e.target後,就可以開始寫紀錄的功能了

function toggleDone(e) {
    // console.log(e.target)
    if (!e.target.matches('input')) return; 

    const el = e.target;
    const index = el.dataset.index;

    items[index].done = !items[index].done;
    localStorage.setItem('items', JSON.stringify(items));
    populateList(items, itemsList);
}

最後最後,別忘了再做一次渲染畫面的動作,
才會是最完整的畫面喔!

今天的練習完成囉,完整的程式碼請直接點擊下方codePen連結
codePen
或者也可以直接到WES BOS的網站下載打包好的檔案
javascript30


上一篇
Day21: LocalStorage(ㄧ)
下一篇
Day23: Mouse Move Shadow
系列文
實作經典 JavaScript 3030
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言