searchHistory

function setHistory (keyword) {    
    let list = localStorage.getItem('historySearch')
    if(list){
      list = JSON.parse(list)
      let index = list.indexOf(keyword)
      if(index!=-1){ // 去重
        list.splice(index, 1)
      }
      list.unshift(keyword)
      if(list.length > 8){ // 最多8條歷史記錄
        list.splice(list.length-1)
      }
      localStorage.setItem('historySearch',JSON.stringify(list))
    }else{
      localStorage.setItem('historySearch',JSON.stringify([keyword]))
    }
}複製代碼
相關文章
相關標籤/搜索