localStorage实现历史记录搜索功能

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

文章目录

  • 为什么使用localStorage
  • 如何使用localStorage
  • 实现历史记录搜索功能(原生JS实现)
    • 效果展示
    • 代码实现


为什么使用localStorage

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

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

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

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

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

如何使用localStorage

二次封装localStorage

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

效果展示

localStorage实现历史记录搜索功能_第1张图片

代码实现

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>
    // 监听dom执行完成后就执行JavaScript代码
    document.addEventListener('DOMContentLoaded', function () {
      // 根据历史记录渲染历史列表
      // 获取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>

    你可能感兴趣的:(JavaScript,javascript,前端,json)