关于localStorage的实际应用

原文链接: https://www.mk2048.com/blog/blog.php?id=h02ai20ak1cb&title=%E5%85%B3%E4%BA%8ElocalStorage%E7%9A%84%E5%AE%9E%E9%99%85%E5%BA%94%E7%94%A8

在客户端存储数据

HTML5 提供了两种在客户端存储数据的新方法:

  • localStorage - 没有时间限制的数据存储
  • sessionStorage - 针对一个 session 的数据存储

之前,这些都是由 cookie 完成的。但是 cookie 不适合大量数据的存储,因为它们由每个对服务器的请求来传递,这使得 cookie 速度很慢而且效率也不高。

在 HTML5 中,数据不是由每个服务器请求传递的,而是只有在请求时使用数据。它使在不影响网站性能的情况下存储大量数据成为可能。

对于不同的网站,数据存储于不同的区域,并且一个网站只能访问其自身的数据。

HTML5 使用 JavaScript 来存储和访问数据。

1.html代码

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>搜索中心</title>
    <link rel="stylesheet" href="assets/mui/css/mui.min.css">
    <link rel="stylesheet" href="assets/fa/css/font-awesome.min.css">
    <link rel="stylesheet" href="css/mobile.css">
</head>
<body>
<div class="lt_container">
    <!--顶部-->
    <header class="lt_topBar">
        <a href="javascript:history.back();" class="mui-icon mui-icon-back left"></a>
        搜索中心
    </header>
    <!--内容-->
    <div class="lt_content">
        <div class="lt_wrapper">
            <!--搜索框-->
            <div class="lt_search">
                <input type="search" placeholder="搜索你喜欢的商品">
                <a href="javascript:;">搜索</a>
            </div>
            <!--历史列表-->
            <div class="lt_history">
                <!--TODO-->
            </div>
        </div>
    </div>
    <!--底部-->
    <footer class="lt_tabs">
        <a href="index.html"><span class="fa fa-home"></span><p>首页</p></a>
        <a href="category.html"><span class="fa fa-bars"></span><p>分类</p></a>
        <a href="user/cart.html"><span class="fa fa-shopping-cart"></span><p>购物车</p></a>
        <a href="user/index.html"><span class="fa fa-user"></span><p>个人中心</p></a>
    </footer>
</div>
<script type="text/template" id="list">
    <% if($data.length){ %>
        <div class="tit">
            <span class="name">搜索历史</span>
            <a class="clear" href="javascript:;"><span class="fa fa-trash"></span>清空历史</a>
        </div>
        <ul>
            <% for(var i = $data.length-1 ; i >=0 ; i --){ %>
                <li><a href="javascript:;" data-key="<%=$data[i]%>"><%=$data[i]%></a><span data-index="<%=i%>" class="fa fa-close"></span></li>
            <% } %>
        </ul>
    <% }else{ %>
        <div class="tit">
            <span class="name">没有搜索历史记录</span>
        </div>
    <% } %>
</script>
<script src="assets/mui/js/mui.min.js"></script>
<script src="assets/zepto/zepto.min.js"></script>
<script src="assets/art-template/template-web.js"></script>
<script src="js/search.js"></script>
</body>
</html>

2.js代码

$(function () {
    $('.lt_search input').val('');
    /*1. 默认渲染当前历史记录*/
    var storageKey = 'leTaoSearchHistoryList';
    /*1.1 需要约定当前网站存历史记录的KEY和数据类型   leTaoSearchHistoryList = '["电脑","手机"]'*/
    var jsonString = localStorage.getItem(storageKey) || '[]';
    var historyList = JSON.parse(jsonString);
    $('.lt_history').html(template('list', historyList));
    //$('.lt_history').html(template('list', {list:historyList,encodeURIComponent:encodeURIComponent}));


    /*2. 点击搜索记录新的搜索历史  跳转去搜索列表页*/
    /*2.1 添加之后  追加在最前面*/
    /*2.2 如果遇见相同的关键字  删除之前的  追加在最前面*/
    /*2.3 当记录的条数超过10条  删除之前的后面的  追加在最前面*/
    $('.lt_search a').on('tap', function () {
        //去除输入的内容  去了两端空格
        var key = $.trim($('.lt_search input').val());
        // 判断是否输入
        if (!key) {
            mui.toast('请输入关键字');
            return false;
        }
        // 有关键字
        /*删除相同的*/
        $.each(historyList, function (i, item) {
            if (item == key) {
                historyList.splice(i, 1);
                /*中断循环*/
                return false;
            }
        });
        /*加载最后*/
        historyList.push(key);
        /*超过10条删掉*/
        if (historyList.length > 10) {
            historyList.splice(0, historyList.length - 10);
        }
        /*存起来*/
        localStorage.setItem(storageKey, JSON.stringify(historyList));
        /*渲染  会跳走 没有必要*/
        //$('.lt_history').html(template('list', historyList));
        /*跳转  传数据转成URL编码*/
        location.href = '/mobile/searchList.html?key=' encodeURIComponent(key);
    })

    /*3. 点击删除  删除当前的历史记录*/
    $('.lt_history').on('tap', 'li span', function () {
        var index = $(this).data('index');
        console.log(index);
        historyList.splice(index, 1);
        /*存起来*/
        localStorage.setItem(storageKey, JSON.stringify(historyList));
        /*渲染  会跳走 没有必要*/
        $('.lt_history').html(template('list', historyList));
    }).on('tap','.clear',function () {
        /*4. 点击清空  清空所有的历史记录*/
        historyList = [];
        localStorage.setItem(storageKey, '[]');
        /*渲染  会跳走 没有必要*/
        $('.lt_history').html(template('list', historyList));
    }).on('tap','li a',function () {
        var key = $(this).data('key');
        /*跳转  传数据转成URL编码*/
        location.href = '/mobile/searchList.html?key=' encodeURIComponent(key);
    });

});

更多专业前端知识,请上 【猿2048】www.mk2048.com

猜你喜欢

转载自blog.csdn.net/qq_45670012/article/details/102753883