使用cookie的一个实例

39 阅读1分钟
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      body {
        text-align: center;
      }
      form {
        display: inline-block;
        margin: 0 auto;
      }
      .left {
        text-align: left;
      }
      .red {
        background-color: red;
      }
      .green {
        background-color: green;
      }
      button {
        padding: 0 5px;
        color: #fff;
        border-radius: 5px;
        border: none;
        margin-top: 10px;
        margin-left: 10px;
      }
      button:hover {
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <form action="#" method="get">
      <table>
        <tr>
          <td>用户名:</td>
          <td>
            <input type="text" name="username" placeholder="请输入用户名" />
          </td>
        </tr>
        <tr>
          <td></td>
          <td class="left">
            <button class="green">登录</button>
            <button class="red">删除</button>
          </td>
        </tr>
      </table>
    </form>
  </body>
  <!-- 点击注册登录和提交按钮会有一个自动提交, -->
  <!-- 清除自动提交 -->
  <script type="module">
    // 封装cookie
    import { setCookie, getCookie, removeCookie } from "./cookie.js";
    // 先找到要点击的button
    const button1 = document.querySelector("button:nth-child(1)");
    const button2 = document.querySelector("button:nth-child(2)");
    const input = document.querySelector("input");
    if (getCookie("username")) {
      input.value = getCookie("username");
    }

    button1.onclick = function (ev) {
      // 阻止默认事件
      ev.preventDefault();
      const username = input.value;
      if (username) {
        setCookie("username", username, 7 * 24 * 3600);
      }
    };
    button2.onclick = function (ev) {
      //阻止默认事件
      ev.preventDefault();
      setCookie("username");
      input.value = "";
    };
  </script>
</html>