Tweety-666
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 【JS30】Day15 - LocalStorage and Event Delegation ###### tags: `LocalStorage`、`Event Delegation`、`querySelector與[ ]`、`reset()`、`客制化 Checkbox` 影片範例中,輸入資料、案button後重整,資料卻還在。這是因為資料有被放入LocalStorage的關係。 ## LocalStorage 首先,做功能的第1步驟,設定好DOM。 如果沒資料庫,又想要保存資料(本地端),那麼可以使用 localStorage 。 localStorage 的使用相當簡單,唯一要注意的是,如果不小心把瀏覽器的快取清空,那麼這些儲存的內容也會一併消失。 下方程式碼中的第三行比較特別。localStorage雖然看起來很像物件(因為裡面的key-value),但localStorage本身存資料的格式是字串。 所以要項目(items)要透過JSON.parse(),把localStorage的資料字串轉成物件。但有可能沒資料,所以會寫```|| []```,若無資料就將items設空陣列。 ```javascript= const addItems = document.querySelector('.add-items'); const itemsList = document.querySelector('.plates'); const items = JSON.parse(localStorage.getItem('items')) || []; ``` DOM處理好後,開始定義函式。 處理過程:先把資料存進items陣列裡(這樣會比較好放),再把items陣列資料存到localStorage跟納入html的畫面裡。 ```javascript= addItems.addEventListener('submit', addItem); //按下按鈕,執行addItem函式 function addItem(e) { e.preventDefault(); //submit原本會讓頁面reload,preventDefault()可以失去此功能 const text = (this.querySelector('[name=item]')).value; const item = { text, //原本是text:text,這是ES6縮寫的寫法 done: false }; items.push(item); //items沒有資料時是空陣列 this.reset(); //input欄位重置 //以下是把資料放進html畫面裡的函式 function populateList(plates = [], platesList) { //plates = []是指參數若沒傳東西進來,預設是空陣列 platesList.innerHTML = plates.map((plate, i) => { return ` <li> <input type="checkbox" data-index=${i} id="item${i}" ${plate.done ? 'checked' : ''} /> <label for="item${i}">${plate.text}</label> </li> `; }).join(''); } populateList(items, itemsList); localStorage.setItem('items', JSON.stringify(items)); //資料存進localStorage } ``` 先單獨把資料放進html畫面裡的函式,拉出來討論: ```javascript= platesList.innerHTML = plates.map((plate, i) => { return ` <li> <input type="checkbox" data-index=${i} id="item${i}" ${plate.done ? 'checked' : ''} /> <label for="item${i}">${plate.text}</label> </li> `; }).join(''); } populateList(items, itemsList); ``` 上方程式碼中,給予每個資料data-index跟id,之後會很方便處理,好比說要刪除,就可以針對點到哪一個data-index進行刪除。 ```${plate.done ? 'checked' : ''}``` 這個寫法很特別。意思是:plate.done這個參數如果是true就加上```'checked'```,若false就加上```''```。 加上```'checked'```,會怎麼樣呢?radio或是checkbox,加上```'checked'```,就會變成選取樣式。 <br> ## Event Delegation 好,到這邊感覺差不多了! 等等,輸入內容後,點擊checkbox,重整頁面,原本checkbox點選的狀態呢?消失了~ 前面也只把items陣列的內容推到localStorage跟放到html畫面上而已,所以重整後,checkbox已經沒有checked,點選的狀態就會消失。 點選清單時我們可以切換資料狀態,一般都是根據DOM,去綁定事件: ```javascript= const lists = document.querySelectorAll('.plates li') lists.forEach(list => { list.addEventListener('click', clickHandler) }) ``` 但這麼做會有一個問題,當我們新增 list 時,這個新增的 list 就不會被綁定到事件。因此這裡我們要使用 **event delegation** 的作法,我們要監聽 ul 的 click 事件,因為當 ul 裡面的 li 被點擊時一樣會觸發這個這個 click 事件(也就是監聽不了新li,那就找它老爸ul),然後我們可以透過 e.target 來篩選和判斷被點擊的元素是誰。 為了讓頁面上點選的狀態持續存在。要進行以下步驟: ```javascript= function toggleDone(e) { if (!e.target.matches('input')) return; // skip this unless it's an input //match也可以寫成is const el = e.target; const index = el.dataset.index; items[index].done = !items[index].done; localStorage.setItem('items', JSON.stringify(items)); populateList(items, itemsList); } itemsList.addEventListener('click', toggleDone); //寫完後,記得要更新localStorage跟html畫面 populateList(items, itemsList); localStorage.setItem('items', JSON.stringify(items)); ``` 針對 element 除了我們可以使用 ```element.querySelector<'selectorString'>``` 來選擇元素外,我們也可以使用 ```element.matches(<'selectorString'>)``` 這個方法。 <br> ## querySelector與[ ] 上方程式碼中,出現這個範例。 ```javascript= const text = (this.querySelector('[name=item]')).value; ``` ```querySelector('[name=item]')```,是指選擇器要選到中括號(```[ ]```)裡面所指的屬性,所以html中,有```name=item```這個屬性,就會被選擇器選擇到。 <br> ## .push() 函式中出現```items.push(item);```,但item是物件,items是陣列,.push()也是陣列的方法。物件可以推到陣列中嗎?答案是可以的。 <br> ## LocalStorage的setItem、getItem、removeItem 可以把LocalStorage想像成裡面是雙欄位的表格,欄位分別是key、value,分別都是填入字串。想像setItem就是設定表單內容。 ```localStorage.setItem('欄位名稱', '欄位內容');``` ```localStorage.setItem('key名稱', 'value名稱');``` 好比說,報名活動要輸入名字、電話。把LocalStorage當成報名表。可以設定成: ```localStorage.setItem('名字', '王阿明');``` ```localStorage.setItem('電話', '0900123456');``` 同理,getItem就是取得表單內容。 ```localStorage.getItem('items')``` 取得表單內欄位的內容。好比說: ```localStorage.getItem('電話')```,這樣就可以拿到電話囉。 想要刪掉資料,可以用```localStorage.removeItem(keyName);``` <br> ## .reset() 使用者填完資料後,輸入,通常input欄位的內容會消失(方便馬上填新資料進去)。 要讓input欄位的內容消失,通常會用```.reset()```。 ```this.reset();```的```this```指的是使用者所選的input。```.reset()```讓它重置。 <br> ## 客制化 Checkbox 影片中間有提到,關於客制化Checkbox的小技巧,先把這裡的checkbox先把它```display:none```,讓它消失在畫面上。再利用 pseudoElement的方式添加假的checkbox。 這招我有用在"[評價星號](https://codepen.io/OneTeam/pen/XBrWOG)"的功能上。 我讓checkbox的content變成星號,滑過、點下去,會變深黑色。常見於簡單的評價功能。 ```css= .plates input + label:before { content: '⬜️'; margin-right: 10px; } .plates input:checked + label:before { content: '🌮'; } ``` <br>

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully