localStorage实现历史记录搜索功能

📝个人主页:爱吃炫迈
💌系列专栏:JavaScript
🧑‍💻座右铭:道阻且长,行则将至💗


为什么使用localStorage

首先我们来对比一下localStorage、sessionStorage和cookie:

cookie最大的问题就是内存问题,cookie的存储空间只有4K,localStorage和sessionStorage可以拓展cookie4K这个限制,一般浏览器支持的是5M大小。

localStorage生命周期是永久,这意味着除非用户显示在浏览器提供的UI上清除localStorage信息,否则这些信息将永远存在。sessionStorage生命周期为当前窗口或标签页,一旦窗口或标签页被永久关闭了,那么所有通过sessionStorage存储的数据也就被清空了。

不同浏览器无法共享localStorage或sessionStorage中的信息。但是在相同浏览器的不同页面间可以共享相同的localStorage(页面属于相同域名和端口),但是不同页面或标签页间无法共享sessionStorage的信息。

由此看来localStorage更加适合我们做历史记录,即使用户关闭浏览器操作,下次进来依旧存在。

如何使用localStorage

二次封装localStorage

实现历史记录搜索功能(原生JS实现)

效果展示

在这里插入图片描述

代码实现

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    ul {
      list-style: none;
      width: 250px;
      position: absolute;
    }

    ul li {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
      border-bottom: 1px dashed #ccc;
    }

    button {
      cursor: pointer;
    }

    div {
      width: 250px;
      text-align: right;
      cursor: pointer;
      font-size: 12px;
    }

    input {
      padding: 5px;
      margin: 10px;
    }
  </style>
</head>

<body>
  <input type="search" placeholder="输入搜索关键字" />
  <input type="button" value="搜索" />
  <div>清空搜索记录</div>
  <ul>
    <li>没有搜索记录</li>
  </ul>

  <script>
      // 根据历史记录渲染历史列表
      // 获取localStorage数据数据是json格式
      var historyListJson = localStorage.getItem('historyList') || '[]'; //historyList预设的键;
      //把json数据转换成数组
      var historyListArr = JSON.parse(historyListJson);

      // 1. 渲染数据
      function render() {
        // 定义一个空html
        var html = '';
        // 遍历数组
        historyListArr.forEach((item, index) => {
          html = `<li><span>${item}</span><button data-index="${index}">删除</button></li>` + html
        });
        // 判断html里面有数据没
        html = html || '<li>没有搜索记录</li>';
        // 把数据渲染到ul里面
        const ul = document.querySelector('ul')
        ul.innerHTML = html
      }
      render();



      // ------------------------------------------------------------------------------------------------------------------------------
      // 2. 点击搜索的时候更新历史搜索记录
      const button = document.querySelector('input[type="button"]');
      button.addEventListener('click', function () {
        // 获取搜索框的内容
        var key = document.querySelector('input').value;

        // 判断点击搜索、搜索框内没有内容提示用户
        if (!key) {
          alert('请输入内容');
          return false;
        }

        // 去重函数
        function killRepeat(val) {
          var kill = 0
          for (let i = historyListArr.length - 1; i >= 0; i--) {
            if (val === historyListArr[i]) {
              kill++
            }
          }
          return kill
        }
        if (killRepeat(key) == 0) {
          // 追加数据到historyListArr数组中
          historyListArr.push(key);
          // 保存更新追加的数据到json数据中
          localStorage.setItem('historyList', JSON.stringify(historyListArr));
          // 渲染数据/直接调用前面的渲染数据函数
          render();
        }

        // 清空搜索框
        document.querySelector('input[type="search"]').value = '';
        // 页面跳转·····
      });




      // ------------------------------------------------------------------------------------------------------------------------
      // 3. 删除数据:因为a的id是动态生成的需要冲ul拿到a的id
      // 获取 ul 元素
      const ul = document.querySelector('ul');
      ul.addEventListener('click', function (event) {
        if (event.target.tagName === 'BUTTON') {
          // 获取点击的 div 元素的id
          const index = event.target.dataset.index;
          // 删除数组内的指定位置数据
          historyListArr.splice(index, 1);

          // 保存更新追加的数据到json数据中
          localStorage.setItem('historyList', JSON.stringify(historyListArr));

          // 渲染数据/直接调用前面的渲染数据函数
          render();
        }
      });



      // ---------------------------------------------------------------------------------------------------------------------------
      // 4. 清除全部历史记录
      const div = document.querySelector('div');
      div.addEventListener('click', function () {
        // 清空数据
        historyListArr = [];

        // 删除空数据
        localStorage.removeItem('historyList');

        // 渲染数据
        render();
      });
  </script>

</body>

</html>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱吃炫迈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值