h5 storage 搜索记录案例

index.html

<!DOCTYPE html>
<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>
</ul>
<script src="jquery.min.js"></script>
<script>
    $(function () {
        //先看本地存储的historyList
        //存储的是json字符串
        var historyListJson=localStorage.getItem('historyList') || '[]';
        //把json字符串格式转换成json对象
        var historyListArr=JSON.parse(historyListJson);
        //数组遍历
        var render = function(){
            var html='';
            historyListArr.forEach(function (item,i) {
                html+='<li><span>'+item+'</span><a data-index="'+i+'"href="javascript:;">删除</a></li>'
            });
            html=html || '<li>没有搜索记录</li>';
            $('ul').html(html);
        };
        render();
        //属性选择器
        $('[type="button"]').on('click',function(){
            var key=$('[type="search"]').val();
            if(!key){
                alert("请输入关键字");
                return false;
            }
            historyListArr.push(key);
            //要把这个数组转换成json格式的字符串
            localStorage.setItem('historyList',JSON.stringify(historyListArr));
            render();
            $('[type="search"]').val('');
        });
        //点击删除一个
        $("ul").on('click','a',function(){
            var index=$(this).data("index");
            historyListArr.splice(index,1);
            localStorage.setItem('historyList',JSON.stringify(historyListArr));
            render();
        });
        //点击全删
        $("div a").on("click",function(){
            historyListArr=[];
            //清空
            //慎用
            //localStorage.clear();
            localStorage.setItem("historyList",'');
            render();
        });
    });
</script>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值