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>
相關文章
相關標籤/搜索