首页 > 技术文章 > 使用localStorage保存搜索记录

JsonShare 2017-07-31 21:53 原文

//过滤一个结果的空记录添加,过滤空搜索  默认保存10条记录,自己可修改
function setHistoryItems(keyword) {
    keyword = keyword.replace("/^\s+|\s+$/g","");
    let { historyIndexSearchItems } = localStorage;
    if (historyIndexSearchItems === undefined) {  
          localStorage.historyIndexSearchItems = keyword;  
    } else {  
          const onlyItem = historyIndexSearchItems.split('|').filter(e => e != keyword);  
          if (onlyItem.length > 0){
              historyIndexSearchItems = keyword + '|' + onlyItem.slice(0,9).join('|');
          }  
          localStorage.historyIndexSearchItems = historyIndexSearchItems;
    }  
}
function clearHistory() {
    localStorage.removeItem('historyIndexSearchItems');   
}

 

推荐阅读