设置他的css样式<h2>历史搜索</h2><input type="text" name="" id="app"><div id="container"></div><script>var historys = [];//event获取输入框的值$("app").keyup(function(event){if(event.keyCode ==13){//console.log(event)var value = $(this).val();if(value){// 只有数组中不包含搜索的值,才添加if(!historys.includes(value)){historys.unshift(value);$("#container").prepend(`<button>${value}</button>`)console.log(historys)$("#app").val("")}else{// 数组中存在的值,至于数组的顶部console.log(value)var index = historys.indexOf(value);// 删除他的下标historys.splice(index,1);// 将下标放在顶部位置historys.unshift(value)console.log(historys)$("#container button").eq(index).remove();$("#container").prepend(`<button>${value}</button>`)$("#app").val("");}}}})</script>
方法二
<h2>历史搜索</h2><input type="text" id="input"><div id="container"></div><script>var historys = []// 回车获取输入框的值$("#input").keyup(function(event){if(event.keyCode==13){var value = $(this).val();if(value){// 只有数组中没有才添加if(!historys.includes(value)){historys.unshift(value);$("#container").prepend(`<button>${value}</button>`)console.log(historys)$("#input").val("")}else{// 将数组中存在的值放在第一个console.log(value)var index = historys.indexOf(value)historys.splice(index,1)historys.unshift(value)console.log(historys)$("#container button").eq(index).remove();$("#container").prepend(`<button>${value}</button>`)$("#input").val("")}}}})</script>
搜索的内容显示再最前面
<input type="text" id="app"><script>// 让数组中被搜索的值至于顶部var arr= ["html","css","js","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>
