• 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>Documenttitle>
      <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 = `
  • ${item}
  • `
    + html }); // 判断html里面有数据没 html = html || '
  • 没有搜索记录
  • '
    ; // 把数据渲染到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>
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
  • 相关阅读:
    MySQL与PostgreSQL对比
    中转服务器是干嘛的?
    界面控件Kendo UI for jQuery R3 2023 - 发布全新金字塔图表类型
    STM32 堆栈空间分布
    数据大航海时代,奇安信如何构筑数据安全的“天盾”?
    苹果iOS系统开发APP应用启动几种速度优化技巧与实践
    RAR压缩包,去除密码?
    Linux的系统进程详解
    BI行业分析思维框架 - 环保行业分析(三)三层经营分析框架
    后端Long型数据传到前端js后精度丢失的问题
  • 原文地址:https://blog.csdn.net/ZhangYu_010228/article/details/133498312