搜索功能在商品不少的時候尤其重要,那爲何要歷史記錄呢,是在意用戶的感覺,節約用戶思路和操做的時候而產生的一項新的功能,那咱們就來討論一些歷史記錄是怎麼實現的?
首先咱們來對比一下localStorage和sessionStorage:瀏覽器
localStorage生命週期是永久,這意味着除非用戶顯示在瀏覽器提供的UI上清除localStorage信息,不然這些信息將永遠存在。session
sessionStorage生命週期爲當前窗口或標籤頁,一旦窗口或標籤頁被永久關閉了,那麼全部經過sessionStorage存儲的數據也就被清空了。spa
不一樣瀏覽器沒法共享localStorage或sessionStorage中的信息。相同瀏覽器的不一樣頁面間能夠共享相同的localStorage(頁面屬於相同域名和端口),可是不一樣頁面或標籤頁間沒法共享sessionStorage的信息。對象
由此看來localStorage更加適合咱們作歷史記錄,即便用戶關閉瀏覽器操做,下次進來依舊存在。blog
localStorage的操做也是極其簡單的:生命週期
- localStorage.setItem("username", "John");
-
- alert( "username = " + localStorage.getItem("username"));
-
-
- localStorage.historyItems = '歷史記錄';
-
- console.log(localStorage.historyItems)
搜索歷史記錄展示形式:
![](http://static.javashuo.com/static/loading.gif)
V1版:rem
- setHistoryItems(keyword) {
- let { historyItems } = localStorage;
- if (historyItems === undefined) {
- localStorage.historyItems = keyword;
- } else {
- const isNotExists = historyItems.split('|').filter((e) => e == keyword).length == 0;
- if (isNotExists) localStorage.historyItems += '|' + keyword;
- }
- }
V2版:get
- setHistoryItems(keyword) {
- let { historyItems } = localStorage;
- if (historyItems === undefined) {
- localStorage.historyItems = keyword;
- } else {
- let historyItems = historyItems.split('|');
- const isExists = historyItems.filter(e => e == keyword).length > 0;
- if (isExists) {
- historyItems = keyword + '|' + historyItems.filter(e => e != keyword).join('|');
- } else {
- historyItems += '|' + keyword;
- }
- localStorage.historyItems = historyItems;
- }
- }
終極版:string
- setHistoryItems(keyword) {
- let { historyItems } = localStorage;
- if (historyItems === undefined) {
- localStorage.historyItems = keyword;
- } else {
- historyItems = keyword + '|' + historyItems.split('|').filter(e => e != keyword).join('|');
- localStorage.historyItems = historyItems;
- }
- }
再次更正版:解決只有一個關鍵字歷史記錄出現空記錄
- setHistoryItems(keyword) {
- keyword = keyword.trim();
- let { historyItems } = localStorage;
- if (historyItems === undefined) {
- localStorage.historyItems = keyword;
- } else {
- const onlyItem = historyItems.split('|').filter(e => e != keyword);
- if (onlyItem.length > 0) historyItems = keyword + '|' + onlyItem.join('|');
- localStorage.historyItems = historyItems;
- }
- }
史記錄關鍵字:域名
- clearHistory() {
- localStorage.removeItem('historyItems');
- }