首页 > 解决方案 > 如何使用“mysite.com/?search=words”概念在返回和第四次导航时记住过滤/搜索结果页面停留的位置?

问题描述

当我单击浏览器中的“后退”按钮或“刷新/重新加载”按钮或“前进”按钮时,我的搜索/过滤结果会消失。如何在返回和第四次导航到页面或使用 mysite.com/?search=words 概念刷新/重新加载时让结果页面与关键字保持一致?

JS

<body>
<script>
var input, table, rows, noMatches, tr, markInstance;

$(document).ready(function init() {
input = document.getElementById('myInput');
noMatches = document.getElementById('noMatches');

table = document.querySelectorAll('#myTable table tr:first-child');
rows = document.querySelectorAll('#myTable table tr');

markInstance = new Mark(table);
if(document.getElementById('myInput').value.length >0){
ContactsearchFX();
}
input.addEventListener('keyup', _.debounce(ContactsearchFX, 250));
});


function ContactsearchFX() {
  resetContent();
  markInstance.unmark({ done: highlightMatches });
}



function resetContent() {
    $('.noMatchErrorText').remove(); 
    //Remove this line to have a log of searches

    //noMatches.textContent = '';
  rows.forEach(function(row) {
    $(row).removeClass('show'); 
  });
}

function highlightMatches() {
  markInstance.mark(input.value, {
    each: showRow,
    noMatch: onNoMatches,
    exclude: ['.nonsearch']
  })
}



function showRow(element) {
//alert(element);
  $(element).parents('tr').addClass('show');              $(element).parents('tr').siblings('tr').addClass('show');
        //Parents incase of several nestings
}



function onNoMatches(text) {
  $('#myInput').after('<p class="noMatchErrorText">No records match: "' +     text +             '"</p>'); 
}



/* Prevents Return/Enter key from doing anything */

$(document).on('submit', 'form', function(e){
/* on form submit find the trigger */
if( $(e.delegateTarget.activeElement).not('input, textarea').length == 0 ){
    /* if the trigger is not between selectors list, return super false */
    e.preventDefault();
    return false;
} 
});    
/* Prevents Return/Enter key from doing anything */    

////

CSS

<style>
.input-wrap  {
  margin-bottom: 12px;
}

#myInput:invalid ~ .hints {
  display: block;
}



#noMatches:empty, #noMatches:empty + .hints {
  display: none;
}


.style1 tr {
  display: none;
}


.style1 .show {
  display: table-row;
}



#myTable table tr:first-child td mark {
background: orange;
font-weight: bold;
color: black;
}
mark {
background: initial;
}    .style1  {
text-align: left;
}
</style>

HTML

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js">
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1
/mark.min.js"></script>
<head>
<body>
<div class="input-wrap">
<label>
Search 
<input id="myInput" type="text" spellcheck="false"
   placeholder="Search Titles"/>
<div class="hintsWrap">
<p id="noMatches"></p>
<p class="hints">
Hints: type "Title1", "Title2", "Title3"...
</p>
</div>
</label>
</div>
<br />
<br />
<br />
<br />
<table id="myTable" style="width: 100%" class="style1">
    <tr>
        <td>
<br />
<br />
<table style="width: 100%">
    <tr>
        <td>
        <table style="width: 100%">
            <tr>
                <th class="style1">Type</th>
                <td>type1</td>
            </tr>
            <tr>
                <th class="style1">Title</th>
                <td>title1</td>
            </tr>
            <tr>
                <th class="style1">Description</th>
                <td>description1</td>
            </tr>
            <tr>
                <th class="style1">Date</th>
                <td>date1</td>
            </tr>
        </table>
        </td>
    </tr>
</table>
<br />
<br />
        <table style="width: 100%">
            <tr>
                <th class="style1">Type</th>
                <td>type2</td>
            </tr>
            <tr>
                <th class="style1">Title</th>
                <td>title2</td>
            </tr>
            <tr>
                <th class="style1">Description</th>
                <td>description2</td>
            </tr>
            <tr>
                <th class="style1">Date</th>
                <td>date2</td>
            </tr>
        </table>
<br />
<br />
        <table style="width: 100%">
            <tr>
                <th class="style1">Type</th>
                <td>type3</td>
            </tr>
            <tr>
                <th class="style1">Title</th>
                <td>title3</td>
            </tr>
            <tr>
                <th class="style1">Description</th>
                <td>description3</td>
            </tr>
            <tr>
                <th class="style1">Date</th>
                <td>date3</td>
            </tr>
        </table>
<br />
<br />

一直在尝试整合这块 JS 并没有太大的成功

let input = document.getElementById('myInput'),
text = '';

// Keyup listener on input field
input.on('keyup', function(e) {
 text = input.value;

  // Add the text change to the browser history so users can go          back/forward,         and save url parameter in the history state
 let historyState = {
'text': text,
}
window.history.pushState(historyState, null, `?search=${text}`);
});


// Run something after History listener finds search text exists
const updateSearch = function(text) {
console.log(`I found the search to be: ${text}`);
}

// History listener
$(window).on('popstate', function(e) {
let state = e.originalEvent.state

 if (state !== null) { //If text exists
 updateSearch(state.text)
 } else { //If no text set (URL has no params)
console.log('no history state found')
 }
});

标签: javascripthtmljquerycss

解决方案


您可以将search参数保存在本地存储(或会话存储)中,也可以GET始终将其保存在您的存储中。

let searchQuery = $(`#id`).val();
// based on either a click or blur event fire
let nQuery= retrieveItems(`interests`, `search`); //this is your GET query string which you assign to your URL
let searchArr = localStorage.getItem(`interests`); // retrieve the original array as an array
searchArr.push(searchQuery); // push the new value into the array
localStorage.setItem(`interests`, searchArr); // override the object property

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

现在,每次您“搜索”某些东西时,它都会将其推送到您的本地存储中(或者再次,您可以将其设为会话存储)。您现在可以遍历该interests属性并将其分配给您href,例如:

function retrieveItems(name, getName)
{
    let searchqueries = localStorage.getItem('interests');
    let urlParam = getName;
    if (searchqueries.length > 0)
    {
        for (let i = 0; i < searchqueries .length; i++)
        {
            //keep in mind you need to insert a character or whatnot to be able to "break" the words the user looked up for.
            urlParam += searchqueries[i];
        }
        return urlParam; //assign this to your 
    }
    return [];
}

现在调用该函数,将返回值绑定到一个变量,然后将其分配给您的href.

注意:我没有对此进行测试,因此它可能包含错误,或者需要进行一些修改。此外,它可能会以一种更简洁的方式完成,但这是一个让你开始的例子。


推荐阅读