本地存储API

一、定义

  • 随着互联网的快速发展,基于网页的应用越来越普遍,同时也变得越来越复杂,为了满足各种各样的需求,会经常在本地存储大量的数据,HTML5规范提出了相关解决方案
  • 本地存储设置读取方便,容量较大,sessionStorage约5M,localStorage约20M,但是只能存储字符串,但是可以将对象JSON.stringify()编码后存储

二、两种存储方式

①window.sessionStorage 生命周期为关闭浏览器窗口,在同一个窗口(页面)下数据可以共享

②window.localStorage   永久生效,除非收到删除(服务器方式访问然后清除缓存),可以多窗口(页面)共享

本地存储API_第1张图片

三、相关方法

①setItem(key,value) 设置存储内容

②getItem(key) 读取存储内容

③removeItem(key)删除键值为key的存储内容

④clear() 清除所有存储内容

本地存储API_第2张图片本地存储API_第3张图片

四、案例:搜索历史记录

DOCTYPE html>
<html lang="en">
<head>
    <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;
        }
        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>
        // 使用json数据存储搜索历史记录;预设一个key为historyList;采用localStorage存储
        $(function(){
            // 1.默认根据历史记录渲染历史列表
            var historyListJson=localStorage.getItem("historyList") ||'[]';
            var historyListArr=JSON.parse(historyListJson);//数组格式的数据
            var render=function(){
                var html='';
                historyListArr.forEach(function(item,index){
                html +='
  • '+item+''+index+'" href="javascript:;">删除
  • ' }); html=html || '
  • 没有搜索记录
  • '; $('ul').html(html); } render(); // 2.点击搜索按钮更新历史记录,并且渲染历史列表 $('[type="button"]').on('click',function(){ var value=$.trim($('[type=search]').val()); if(!value){ alert('请输入搜索关键字'); return false; } historyListArr.push(value);//追加一条历史记录 localStorage.setItem('historyList',JSON.stringify(historyListArr));//保存 render();//渲染 $('[type=search]').val('');//清空搜索框 }); // 3.点击删除按钮删除对应的历史记录,并且渲染历史列表 $('ul').on('click','a',function(){ var index=$(this).data('index'); historyListArr.splice(index,1);//删除 localStorage.setItem('historyList',JSON.stringify(historyListArr));//保存 render();//渲染一次 }); // 4.点击清空历史记录,清空所有的历史记录并渲染历史列表 $('div a').on('click',function(){ historyListArr=[];//清空,localStorage.clear()慎用 localStorage.setItem('historyList',''); render(); }); }) script> body> html>

    本地存储API_第4张图片

    转载于:https://www.cnblogs.com/EricZLin/p/9261445.html

    你可能感兴趣的:(本地存储API)