如何使用Javascript在浏览器中存储各输入框最近20条搜索历史
实现方案
我们使用浏览器自带的localStorage做持久化存储,为每个输入框分配独立的存储key,实现历史记录读写、自动去重、最多保留20条的逻辑,修改原有代码如下:
第一步:先定义通用的历史记录读写工具函数
// 读取指定输入框的搜索历史 function getSearchHistory(inputId) { const history = localStorage.getItem(`search_history_${inputId}`); return history ? JSON.parse(history) : []; } // 保存搜索关键词到指定输入框的历史,自动去重、最多保留20条 function saveSearchHistory(inputId, keyword) { // 空关键词不存储 if (!keyword.trim()) return; let history = getSearchHistory(inputId); // 先移除已存在的相同关键词,避免重复 history = history.filter(item => item !== keyword.trim()); // 新搜索的关键词放在历史最顶部 history.unshift(keyword.trim()); // 超过20条就删除最早的历史 if (history.length > 20) { history = history.slice(0, 20); } localStorage.setItem(`search_history_${inputId}`, JSON.stringify(history)); }
第二步:修改原有jQuery自动补全代码
$("input[type='text']").autocomplete({ source: function(request, response) { const inputId = $(this.element).prop("id"); // 输入框无内容时直接返回本地搜索历史 if (!request.term.trim()) { response(getSearchHistory(inputId)); return; } // 有输入内容时走原有AJAX逻辑拉取接口数据 var params = {'page':1,'size':"10"}; params[inputId] = request.term; var jsonParams = JSON.stringify(params); $.ajax({ type: "POST", url:"http://localhost:5645/search", data: jsonParams, headers: {"X-CSRF-TOKEN": $("input[name='_csrf']").val()}, contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { var result=[]; for(var i = 0; i < msg.details.length; i++) { var obj = msg.details[i]; if(obj!=null && columnMapping[inputId]!=undefined && obj[columnMapping[inputId]]!=undefined){ result.push(obj[columnMapping[inputId]]); } } response(result); } }) }, select: function(event, ui) { if(ui.item) { const inputId = $(this).prop("id"); // 选中的关键词存入本地历史 saveSearchHistory(inputId, ui.item.label); alert("You picked '" + ui.item.label); } else { alert("Nothing selected, input was " + this.value); } return false; } }).autocomplete("instance")._renderItem = function(ul, item) { var item = $("<div>" + item.label + "</div>") return $("<li>").append(item).appendTo(ul); };
补充说明
- 如果需要浏览器关闭后就清空历史,把代码中所有
localStorage替换为sessionStorage即可 - 如果需要用户输入内容直接回车提交也保存历史,可以给输入框绑定回车事件,调用
saveSearchHistory保存当前输入值即可
内容的提问来源于stack exchange,提问作者rahul
相关产品推荐
相关产品推荐

