localStorage的写法

196 阅读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>
  </head>
  <body>
    <script>
      // 写入内容
      localStorage.setItem("username", "zhangsan");
      //   也可以简写
      localStorage.sex = "male";
      //   获取内容

      console.log(localStorage.getItem("username"));
      //   可以简写
      console.log(localStorage.sex);
      //   清空
      localStorage.clear();
    </script>
  </body>
</html>

<!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>
  </head>
  <body>
    <script>
      let count = 0;
      if (localStorage.getItem("count")) {
        count = localStorage.getItem("count");
      }
      //   count自增
      count++;
      // setItem()是往localStorage中添加内容,
      // 里面有2个参数,一个名字,一个是值
      localStorage.setItem("count", count);
      document.write(`这是您第${count}次访问页面`);
    </script>
  </body>
</html>