实现搜索框的history,可以向前回退,与向后回退
<input type="search" name="" id="search"><button id="btn" onclick="search()">btn</button><div id="text"></div><script>const obj = [{name: "js"}, {name: 'css'}, {name: "html"}]const inp = document.getElementById('search');const text = document.getElementById('text')function search() {const inpValue = inp.value;const isFind = obj.filter(function (item) {if (item.name.indexOf(inpValue) > -1) {text.innerText = inpValue;history.pushState({Val:inpValue},null , "#" + inpValue);}})// 当url发生改变的时候触发window.addEventListener('popstate',function(e){// console.log(e)inp.value = text.innerText = e.state === null ? " " : e.state.Val;})// hash值发生改变才会触发,锚点改变才会触发 相对于popstate的触发先后顺序为 先触发popstate后触发hashchangewindow.addEventListener("hashchange",function(e){inp.value = text.innerText = e.state === null ? " " : e.state.Val;})}</script>
