使用localStorage实现登录界面自动填充 记住用户名效果

110 阅读1分钟

和cookie一样,open withliveserver 打开浏览器,点开application,下面有cookie和localstorage

cookie要记住用户名效果,需要封装cookie的添加setCookie,获取getCookie和删除removeCookie

localStorage里面,自带了添加、获取和删除localStorage的属性,不用封装引入。

cookie是关闭浏览器或者设置失效时间maxAge删除存入的cookie,而localStorage永久存储,除非手动删除 localStorage.removeItem("要删除的属性名")或者全删localStorage.cle()

具体代码如下

<!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;
      }
      /* 表单inline-bolock */
      form {
        display: inline-block;
        margin: 0 auto;
      }
      .left {
        text-align: left;
      }
      .green {
        background-color: green;
      }
      .red {
        background-color: red;
      }
      button {
        border: none;
        color: #fff;
        border-radius: 5px;
        padding: 5px 10px;
        margin-top: 10px;
        margin-right: 10px;
      }
      button:hover {
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <!-- for表单 get提交 -->
    <form action="#" method="get">
      <!--table  -->
      <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>
    const button1 = document.querySelector("button:nth-of-type(1)");
    const button2 = document.querySelector("button:nth-of-type(2)");
    const input = document.querySelector("input");
    // 点击之前或者点击之后,如果localStorage里面有值,就把这个值显示到input框里
    if (localStorage.getItem("username")) {
      input.value = localStorage.getItem("username");
    }
    // 添加点击事件
    // 登录
    button1.onclick = function (e) {
      // 先清除默认事件
      e.preventDefault();

      // 点击的时候,把input的值存到localStorage里面
      const username = input.value;
      localStorage.setItem("username", username);
    };
    // 删除按钮
    button2.onclick = function (e) {
      e.preventDefault();
      //   点击了删除,就删除localStorage里面的数据
      localStorage.clear();
      //   input框里面的值也没有了
      input.value = "";
    };
  </script>
</html>