实现搜索框的history,可以向前回退,与向后回退

    1. <input type="search" name="" id="search">
    2. <button id="btn" onclick="search()">btn</button>
    3. <div id="text">
    4. </div>
    5. <script>
    6. const obj = [{
    7. name: "js"
    8. }, {
    9. name: 'css'
    10. }, {
    11. name: "html"
    12. }]
    13. const inp = document.getElementById('search');
    14. const text = document.getElementById('text')
    15. function search() {
    16. const inpValue = inp.value;
    17. const isFind = obj.filter(function (item) {
    18. if (item.name.indexOf(inpValue) > -1) {
    19. text.innerText = inpValue;
    20. history.pushState({Val:inpValue},null , "#" + inpValue);
    21. }
    22. })
    23. // 当url发生改变的时候触发
    24. window.addEventListener('popstate',function(e){
    25. // console.log(e)
    26. inp.value = text.innerText = e.state === null ? " " : e.state.Val;
    27. })
    28. // hash值发生改变才会触发,锚点改变才会触发 相对于popstate的触发先后顺序为 先触发popstate后触发hashchange
    29. window.addEventListener("hashchange",function(e){
    30. inp.value = text.innerText = e.state === null ? " " : e.state.Val;
    31. })
    32. }
    33. </script>