JavaScript_Html5_LocalStorage項目demo

項目中localStorage實用

項目中h5本地存儲的一個小實用,本意使用cookie,但發現chrome調試被禁用,便用了localStorage.javascript


此需求是一貼吧搜索頁,在新用戶第一次點擊搜索框時爲搜索頁面,老用戶點擊搜索框時帶有搜索記錄,實現方法爲在點擊搜索按鈕時便爲用戶建立一個本地存儲localStorage user-data,判斷當頁面中含有user-data時便將搜索框的val追加進user-data中,以「|」隔開,若user-data不存在便建立user-data。css

var storage=window.localStorage;
if(storage.getItem("user-data")){
    var str=storage.getItem("user-data");
    storage.setItem("user-data",str+'|'+$('#keyword').val());
}else{
    storage.setItem("user-data",$('#keyword').val());
}

當頁面加載時若本地localStorage中含有user-data,則獲取此數據,返回爲字符串,用split方法以「|」爲判斷條件將此字符串切割爲數組,並循環建立,導入頁面編輯器中,即:html

if($('.search-con') && !findKey('keyWords')){
        var html="";
        if(window.localStorage && localStorage.getItem("user-data")){
            var data=localStorage.getItem("user-data").split('|');
            for(var i=data.length-1;i>=0;i--){
                html+="<div class='user-his'>"+data[i]+"</div>"
            }
            $('.user-clear').show();
        }else{
            html='<i class="iconfont icon-wenbensousuo"></i><br><span>未搜索任何信息</span>'
        }
        $('.search-con').html(html);
    }

其中findKey()方法爲判斷路徑中是否含有搜索關鍵字keyWords,需求是當含有搜索關鍵字時顯示爲搜索結果,無需關注。java

function findKey(name){
        var str=window.location.href;
        return str.indexOf(name)==-1?false:true;
    }

點擊清除搜索記錄時清除user-data,即:jquery

localStorage.removeItem("user-data");

點擊搜索時將搜索框val拼入路徑,頁面刷新獲取後臺數據,減小ajax請求,search.html爲相對路徑,便是當前文件名便可:web

window.location.href='search.html?keyWords='+encodeURI($('#keyword').val());

實現此需求只需後端一個頁面便可(咱們後端爲asp.net),貼出完整測試代碼:ajax

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Cache-Control" content="no-cache">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
    <meta content="black" name="apple-mobile-web-app-status-bar-style">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <link href="http://img.pccoo.cn/wap/webapp/font/iconfont.css" rel="stylesheet">
    <script type="text/javascript" src="http://img.pccoo.cn/wap/js2/jquery.js?v1.0"></script>
    <title>論壇搜索</title>
    <style>
        /*2016-12-1 wm*/
        *{padding:0;margin:0;}
        li{list-style: none}
        input{outline: none}
        .s-content{background:#fff;padding:10px;position:relative;height:30px;border-bottom:1px solid #e5e5e5;}
        .sear-wrap{display:-webkit-box;display:flex;width:80%;padding:5px; border-radius:20px;background:#f0f0f0;position:absolute;top:20%;left:10px;z-index:9;}
        .sear-wrap input[type=text] {  display:block;-webkit-box-flex:1;flex:1;height:24px;line-height:24px;color:#666;border:none;background:none;text-indent:10px;}
        .s-content .tishi{position:absolute;right:10px;top:16px;color:#09f;font-size: 14px}
        .search-con{width: 100%;background: #fff;text-align: center;}
        .search-con i{margin-top:100px;font-size: 80px;background: #f0f0f0;border-radius: 50%;width: 160px;height: 160px;display: inline-block;line-height: 160px;color:#ddd;}
        .search-con span{margin-top:10px;color:#ccc;display: inline-block;}
        .search-con .user-his{width: 100%;height: 40px;color:#333;line-height: 40px;text-align:left;padding-left:10px;font-size: 16px;border-bottom:1px solid #eee;}
        .user-clear{width: 90px;height: 30px;border-radius: 10px;font-size:14px;color:#09f;border:1px solid #09f;margin:20px auto;line-height: 30px;padding:0 10px;display: none}
        #span_search{width:30px;text-align: center;}
        #span_search i{color:#ccc;}
        #span_search i.icon-guanbi1{color:#ccc;}
        .srhword {position: absolute;top: 100px;border-radius: 0 0 3px 3px;width: 95%;z-index: 20;background: #fff;overflow-y: auto;_display: none;padding:10px 10px 40px;}
        .srhword li{padding:0px 0 10px;border-bottom:1px solid #eee;}
        .srhword .end-title{color:#999;margin:10px 0;font-size: 16px;border:none;}
        .srhword span{color:red;}
        .srhword .p1{color:#333;font-size: 16px;line-height: 26px;word-break: break-all;text-overflow: ellipsis;display: -webkit-box;-webkit-box-orient: vertical; -webkit-line-clamp: 2;overflow: hidden;  }
        .srhword .p2{color:#ccc;font-size: 12px;margin-top:10px;position:relative;}
        .srhword .p2 i{font-size: 12px;margin-right:10px;}
        .srhword .p2 em{position:absolute;right:10px;}
        .load-more{position:absolute;bottom:0;left:0;line-height: 40px;text-align: center;width: 100%;background: #f0f0f0;}
        .load-more img{vertical-align: middle;}
        header dl dd.right-search{position:absolute;top:0;right:80px;}
        header dl dd.right-search i{font-size: 37px;color:#fff;}
    </style>

</head>
<body>
<section class="s-content">
    <form action="" method="get">
        <div class="sear-wrap">
            <input type="text" class="inp_srh" name="keyword" id="keyword" placeholder="請輸入帖子關鍵詞" maxlength="20">
            <span id="span_search"><i class="iconfont icon-search1"></i></span>
        </div>
        <span class="tishi">搜索</span>
    </form>
</section>
<section class="search-con">

    <!-- <i class="iconfont icon-search1"></i>
    <br>
    <span>未搜索任何信息</span> -->
    <!-- <div class="user-his">范冰冰</div> -->
</section>
<div class="user-clear">清除搜索記錄</div>
<!-- <div class="load-more">加載更多</div> -->
<script>
    //判斷頁面地址中是否含有key
    if(findKey("keyWords")){
        $(document).find('.search-con').attr('class','srhword').removeClass('search-con');
        var key=window.location.search;
        $('.srhword').html('<li class="end-title">關於<span> "汽車" </span>的搜索結果</li>\
            <!-- <li class="end-title">未找到關於<span> "汽車" </span>的相關信息</li> -->\
            <li>\
                <p class="p1">悄悄的進村,<span>汽車</span>悄悄的進村,悄悄的進村,悄悄的進村悄悄的進村悄悄的進村悄悄的進村,悄悄的進村,悄悄的進村,</p>\
                <p class="p2"><i class="iconfont icon-touxiang"> 抹臉花看</i><i class="iconfont icon-xiaoxi2"> 23</i> 2分鐘前</p>\
            </li>\
            <li>\
                <p class="p1">悄悄的進村,<span>汽車</span>悄悄的進村,悄悄的進村,悄悄的進村悄悄的進村悄悄的進村悄悄的進村,悄悄的進村,悄悄的進村悄悄的進村悄悄的進村悄悄的進村悄悄的進村,悄悄的進村,悄悄的進村悄悄的進村悄悄的進村悄悄的進村悄悄的進村,悄悄的進村,悄悄的進村,</p>\
                <p class="p2"><i class="iconfont icon-touxiang"> 抹臉花看</i><i class="iconfont icon-xiaoxi2"> 23</i> 2分鐘前</p>\
            </li>\
            <li>\
                <p class="p1">悄悄的進村,<span>汽車</span>悄悄的進村,悄悄的進村,悄悄的進村悄悄的進村悄悄的進村悄悄的進村,悄悄的進村,悄悄的進村悄悄的進村悄悄的進村悄悄的進村悄悄的進村,悄悄的進村,悄悄的進村悄悄的進村悄悄的進村悄悄的進村悄悄的進村,悄悄的進村,悄悄的進村,</p>\
                <p class="p2"><i class="iconfont icon-touxiang"> 抹臉花看</i><i class="iconfont icon-xiaoxi2"> 23</i> 2分鐘前</p>\
            </li>\
            <li>\
                <p class="p1">悄悄的進村,<span>汽車</span>悄悄的進村,悄悄的進村,悄悄的進村悄悄的進村悄悄的進村悄悄的進村,悄悄的進村,悄悄的進村悄悄的進村悄悄的進村悄悄的進村悄悄的進村,悄悄的進村,悄悄的進村悄悄的進村悄悄的進村悄悄的進村悄悄的進村,悄悄的進村,悄悄的進村,</p>\
                <p class="p2"><i class="iconfont icon-touxiang"> 抹臉花看</i><i class="iconfont icon-xiaoxi2"> 23</i> 2分鐘前</p>\
            </li>\
            <li>\
                <p class="p1">悄悄的進村,<span>汽車</span>悄悄的進村,悄悄的進村,悄悄的進村悄悄的進村悄悄的進村悄悄的進村,悄悄的進村,悄悄的進村悄悄的進村悄悄的進村悄悄的進村悄悄的進村,悄悄的進村,悄悄的進村悄悄的進村悄悄的進村悄悄的進村悄悄的進村,悄悄的進村,悄悄的進村,</p>\
                <p class="p2"><i class="iconfont icon-touxiang"> 抹臉花看</i><i class="iconfont icon-xiaoxi2"> 23</i> 2分鐘前</p>\
            </li>\
            <li>\
                <p class="p1">悄悄的進村,<span>汽車</span>悄悄的進村,悄悄的進村,悄悄的進村悄悄的進村悄悄的進村悄悄的進村,悄悄的進村,悄悄的進村悄悄的進村悄悄的進村悄悄的進村悄悄的進村,悄悄的進村,悄悄的進村悄悄的進村悄悄的進村悄悄的進村悄悄的進村,悄悄的進村,悄悄的進村,</p>\
                <p class="p2"><i class="iconfont icon-touxiang"> 抹臉花看</i><i class="iconfont icon-xiaoxi2"> 23</i> 2分鐘前</p>\
            </li>\
            <li>\
                <p class="p1">悄悄的進村,<span>汽車</span>悄悄的進村,悄悄的進村</p>\
                <p class="p2"><i class="iconfont icon-touxiang"> 抹臉花看</i><i class="iconfont icon-xiaoxi2"> 23</i> 2分鐘前</p>\
            </li>\
            ')
        $('.srhword').append('<div class="load-more">加載更多</div>');
        // match(/aaa(\S*)/)[1]
        key=key.match(/=(\S*)/)[1];
        $.ajax({
            url:'',
            type:'get',
            autoChange: true,
            data: { 'key': key},
            success:function(data){

            },
            error:function(){}
        })
    }
    //判斷網頁地址中是否包含key
    function findKey(name){
        var str=window.location.href;
        return str.indexOf(name)==-1?false:true;
    }
    //點擊清除清空輸入框內容
    $('#span_search').on('click',function(){
        if($('#span_search').find("i").hasClass("icon-guanbi1")){
            $("#keyword").val("");
            $('#span_search i').removeClass('icon-guanbi1').addClass('icon-search1');
        }
    })
    //輸入內容時顯示清除按鈕
    $('#keyword').keyup(function(){
        $('#span_search i').removeClass('icon-search1').addClass('icon-guanbi1');
    })
    //判斷若是有本地數據緩存生成列表
    if($('.search-con') && !findKey('keyWords')){
        var html="";
        if(window.localStorage && localStorage.getItem("user-data")){
            var data=localStorage.getItem("user-data").split('|');
            for(var i=data.length-1;i>=0;i--){
                html+="<div class='user-his'>"+data[i]+"</div>"
            }
            $('.user-clear').show();
        }else{
            html='<i class="iconfont icon-wenbensousuo"></i><br><span>未搜索任何信息</span>'
        }
        $('.search-con').html(html);
    }
    //點擊搜索記錄刷新頁面
    $('.search-con').find('div').on('click',function(){
        window.location.href='search.html?keyWords='+encodeURI($(this).text());
    })
    //點擊搜索按鈕將搜索內容存入本地
    $('.tishi').on('click',function(){
        if(window.localStorage && $('#keyword').val()!=""){
            var storage=window.localStorage;
            if(storage.getItem("user-data")){
                var str=storage.getItem("user-data");
                storage.setItem("user-data",str+'|'+$('#keyword').val());
            }else{
                storage.setItem("user-data",$('#keyword').val());
            }
        }
        // var reg=/\?(.*?)\=/g;
        // 將搜索內容傳入url刷新頁面
        if($('#keyword').val()!=""){
            window.location.href='search.html?keyWords='+encodeURI($('#keyword').val());
        }
    })
    //點擊清除本地存儲
    $('.user-clear').on('click',function(){
        localStorage.removeItem("user-data");
        $('.search-con').remove("div");
        $(this).hide();
        window.location.href=window.location.href;
    })
    //滑動加載下一頁
    if($('.load-more') && $('.load-more').offset().top<$(window).height()){
        $('.srhword').find('.load-more').html('沒有更多內容了。。')
    }
    $(window).scroll(function(){
        if($(document).scrollTop()+$(window).height()>=$('.load-more').offset().top){
            var flag=true,
            pageIndex=0;
            if(!flag)return;
            flag=!flag;
            pageIndex++;
            $('.srhword').find('.load-more').html("<img src='http://img.pccoo.cn/wap/images/load.gif' />正在加載,請稍後…")
            $.ajax({
                url:'',
                type:'get',
                autoChange: true,
                data: { 'key': key,'pageIndex':pageIndex},
                success:function(data){
                    if(data){
                        $('.srhword').find('.load-more').before(data);
                        $('.srhword').find('.load-more').html('滑動加載更多')
                    }else{
                        $('.srhword').find('.load-more').html('沒有更多內容了。。')
                    }
                    flag=!flag;
                },
                error:function(){}
            })
        }
    })

</script>
</body>
</html>

直接複製到本地即可測試,調試狀態爲移動端效果更佳,若是路徑中含有keyWords則爲測試數據,將.html後面的數據刪除便是搜索頁面。
如有疑問或錯誤,請多多交流,謝謝~~chrome

相關文章
相關標籤/搜索