1、让数组中被搜索的值,至于顶部
<script> /* 让数组中被搜索的值,至于顶部 */ var arr= ["html","css","js","vue","react"] /* ["js","html","css","vue","react"] */ $("#app").keyup( function(event){ if(event.keyCode==13){ var value = $(this).val(); if(arr.indexOf(value)!=-1){ console.log(value) var index = arr.indexOf(value); arr.splice(index,1); arr.unshift(value); console.log(arr); } } }) </script>
2、历史搜索
<script> /* 1、获取输入框的值 */ var historys = []; $("#app").keyup(function (event) { if (event.keyCode == 13) { /* 2.将值添加到一个数组里面去 */ var value = $(this).val(); var template = ` <button>${value}</button> ` /* 只有数组中不包含输入的关键字才向数组添加 */ if (value) { if (!historys.includes(value)) { historys.unshift(value); /* 3、渲染数据到页面 */ $("#container").prepend(template) $(this).val("") } else { var index = historys.indexOf(value); var res = historys.splice(index, 1); historys.unshift(...res); console.log(historys) $("button").eq(index).remove(); $("#container").prepend(template) $(this).val("") } } } }) </script>