本地储存(localStorage,sessionStorage),cookies(历史记录储存)

特性

  • 设置、读取方便
  • 容量较大,sessionStorage约5M、localStorage约20M
  • 只能存储字符串,可以将对象JSON.stringify() 编码后存储

  • window.sessionStorage
    • 生命周期为关闭浏览器窗口
    • 在同一个窗口(页面)下数据可以共享
  • window.localStorage
    • 永久生效,除非手动删除(服务器方式访问然后清除缓存)
    • 可以多窗口(页面)共享

方法

  • setItem(key, value) 设置存储内容
  • getItem(key) 读取存储内容
  • removeItem(key) 删除键值为key的存储内容
  • clear() 清空所有存储内容

小栗子——模拟历史记录储存


<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>首页title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        body{
            margin-left: 300px;
        }
        ul{
            list-style: none;
        }
        ul li,div{
            width: 250px;
            padding: 10px 0;
            margin-left: 10px;
            border-bottom: 1px dashed #ccc;
            height: 20px;
        }
        a{
            float: right;
        }
        input{
            padding: 5px;
            margin: 10px;
        }
    style>
head>
<body>
<input type="search" placeholder="输入搜索关键字"/>
<input type="button" value="搜索"/>
<div><a href="javascript:;">清空搜索记录a>div>
<ul>
    <li>没有搜索记录li>
    <li><span>手机span><a href="javascript:;">删除a>li>
    <li><span>手机span><a href="javascript:;">删除a>li>
    <li><span>手机span><a href="javascript:;">删除a>li>
    <li><span>手机span><a href="javascript:;">删除a>li>
    <li><span>手机span><a href="javascript:;">删除a>li>
ul>
<script src="jquery.min.js">script>
<script>
    $(function () {
        /*1.默认根据历史记录渲染历史列表*/
        var historyListJson=localStorage.getItem('historyList')||'[]';
        var historyListArr = JSON.parse(historyListJson);
        var render =function () {
            var html='';
            historyListArr.forEach(function (item,i) {
                html+='
  • '+item+'+i+'" href="javascript:;">删除
  • '
    }); html=html||'
  • 没有搜索记录
  • '
    ; $('ul').html(html); } render(); /*2.点击搜索的时候更新历史记录渲染列表*/ $('[type="button"]').on('click',function () { let key=$.trim($('[type="search"]').val());//trim去除左右空字符串 if (!key){ alert('请输入关键字'); return false } /*追加一条历史*/ historyListArr.push(key); //保存到localStorage localStorage.setItem('historyList',JSON.stringify(historyListArr)); //渲染 render(); $('[type="search"]').val(''); }); /*3.点击删除的时候删除对应的历史记录渲染列表*/ $('ul').on('click','a',function () { let index=$(this).data('index');//拿到自定义属性的下标 historyListArr.splice(index,1);//del localStorage.setItem('historyList',JSON.stringify(historyListArr));//保存 render(); }); /*4.点击清空的时候清空历史记录渲染列表*/ $('div>a').on('click',function () { historyListArr=[];//初始化内存里的数据 localStorage.setItem('historyList',''); render(); }); });
    script> body> html>

    你可能感兴趣的:(web前端)