# [JS30] Day.15 LocalStorage and Event Delegation ###### tags: `JS30` ## 任務 Task 製作出類似 `todolist` 的清單,可以增加項目勾選,並將資料儲存於 `localStorage` 重新打開網頁後,項目依然存在。 ==完成時間:2hr== ## 步驟 Step 1. 建立 `function addItems()` 將輸入的文字放入 `array`。 2. 建立 `function populateList()` 將輸入文字顯示於清單上。 3. 使用 `localStorage.setItem` 將清單資料存入。 4. 建立 `function toggleDone()` 紀錄被勾選的項目,並存入 `localSorage`。 ## 筆記 Note ### <font color=#337EA9>CSS 置換 `checkbox` 方法</font> * 在 `input` 前面加偽類 `label` 標籤 ```css= .plates input { display: none; } .plates input + label:before { content: "⬜️"; } .plates input:checked + label:before { content: "🌮"; } ``` ### <font color=#337EA9>JS localStorage</font> * 將資料存於目前文件的 `Storage` 中 * 以 `string` 形式做儲存,通常有 `Array` 時,會使用 `JSON.stringify(Array)` 的方式轉換為 `string` ,要使用時則用 `JSON.parse(string)` 轉換回來。 * 常見的另一個為 `sessionStorage` 不同的地方在於, `localStorage` 可以長期保留,而 `sessionStorage` 於頁面被關閉時則被清除。 * `localStorage` 與 `sessionStorage` 皆無法跨瀏覽頁存取。 * 常見 `method`: * `localStorage.setItem('key', 'value')` :新增資料 * `localStorage.getItem('key')`:讀取資料 * `localStorage.removeItem('key')`:刪除指定資料 * `localStorage.clear()`:清除所有資料 ### <font color=#337EA9>JS Element.matches(selectorString)</font> * 符合字串的選擇器,回傳 `true` * `selectorString` 為 `CSS` 選取器。 ### <font color=#337EA9>JS event delegation</font> * 因為有 `Event Bubbling` 才能使用的方法。 * 當遇到子項目較多,或子項目數量會更動時,會選取父層項目做監聽,進而減少監聽的數目。 ### <font color=#337EA9>JS Event.preventDefault</font> * 阻止事件的預設行為,但不會停止事件的行為。 ## 想法 Idea :::warning :bulb: <font color=black>製作出一個 `todoList` 有刪除及日期的功能。 </font> ::: <iframe height="300" style="width: 100%;" scrolling="no" title="Untitled" src="https://codepen.io/jim876633/embed/VwXZmyq?default-tab=" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/jim876633/pen/VwXZmyq"> Untitled</a> by Jim (<a href="https://codepen.io/jim876633">@jim876633</a>) on <a href="https://codepen.io">CodePen</a>. </iframe>