JS增删改查localStorage实现搜索历史功能

    <script type="text/javascript">
        var referrerPath = "@ViewBag.ReferrerPath";//这个是获取来源页的相对路径
        var localStorageKey = "search_history";

        $(document).ready(function () {
            //搜索时记录搜索关键字
            $("#imgSearch").click(function () {
                var keyword = $("#keyword").val();
                setSearchHistory(keyword);
                location.href = referrerPath + "?keyword=" + keyword;
            });

            //显示搜索记录
            showSearchHistory();

            //删除搜索记录
            $("#spanDelete").click(function () {
                localStorage.removeItem(localStorageKey);
                $(".history_search").html("");
            });

            function setSearchHistory(keyword) {
                var items = getSearchHistory();
                if (items.length > 100) {
                    alert("搜索记录太多,请先清空。");
                    return;
                }

                var item = { referrerPath, keyword};

                for (var i = 0; i < items.length; i++) {
                    if (items[i].referrerPath === item.referrerPath && items[i].keyword === item.keyword) {
                        return;
                    }
                }

                items.push(item);
                var strItems = JSON.stringify(items);
                localStorage.setItem(localStorageKey, strItems);
            }

            function getSearchHistory() {
                var strItems = localStorage.getItem(localStorageKey);
                var items = JSON.parse(strItems);
                if (items === null) {
                    items = [];
                }
                return items;
            }

            function showSearchHistory() {
                var arrProductSearchHistroy = new Array();
                $.each(getSearchHistory(), function (i, o) {
                    var url = o.referrerPath + "?keyword=" + o.keyword;
                    var item = "<li><a href=\""+url+"\">" + o.keyword + "</a></li>";
                    arrProductSearchHistroy.push(item);
                });
                $(".history_search").html(arrProductSearchHistroy.join(""));
            }
        });
    </script>

 

posted @ 2019-05-23 13:43  屌丝大叔的笔记  阅读(1341)  评论(0编辑  收藏  举报