iT邦幫忙

0

2024 IT鐵人賽 Day29 -第三方套件js-cookie

  • 分享至 

  • xImage
  •  

推薦使用js-cookie

js-cookie

  • 環境配置 CDN 或 套件命令 npm i js-cookie

語法

  • 儲存
Cookies.set('name', 'value')
  • 儲存(效期)
Cookies.set('name', 'value', { expires: 7 })
  • 讀取cookie
Cookies.get('name')

-刪除cookie

Cookies.remove('name')
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h2 class="textContent"></h2>

    <button class="SaveBtn">儲存</button>
    <button class="DeleteBtn">刪除</button>

    <script>
      const SaveBtn = document.querySelector(".SaveBtn");
      console.log(SaveBtn);
      const DeleteBtn = document.querySelector(".DeleteBtn");
      console.log(DeleteBtn);
      const textContent = document.querySelector(".textContent");
      console.log(textContent);

      SaveBtn.addEventListener("click", () => {
        //  儲存
        console.log("有觸發");
        Cookies.set("text", "我被儲存");
        const cat = Cookies.get("text");
        textContent.innerHTML = cat;
      });

      DeleteBtn.addEventListener("click", () => {
        //  移除顯示
        console.log("有觸發");
        Cookies.remove("text");

        textContent.innerHTML = "";
      });
    </script>
    <script src="https://cdn.jsdelivr.net/npm/js-cookie@3.0.5/dist/js.cookie.min.js"></script>
  </body>
</html>

https://ithelp.ithome.com.tw/upload/images/20241026/20169661ItKCc8BBqm.png


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言