Filter list based on URL hash string

2019-09-03 01:11发布

问题:

I have a list named myul (whatever)

<ul id="myul">
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
    <li>item 4</li>
    <li>item 5</li>
    <li>item 6</li>
</ul>

and i filter its item using <input id="filter" type="text" value=""/>

and script is based on jquery


    jQuery.expr[':'].containsLower = function(a, i, m) {
      return jQuery(a).text().toUpperCase()
         .indexOf(m[3].toUpperCase()) >= 0;    // for uppercase-lowercase support
    };

    $('#filter').keyup(function(){
      $('ul#myul li').hide().filter(':containsLower("'+this.value+'")').fadeIn(); 

    // shows only the items that have input value and that too on keyup function
    });

it can filter the list on key up function, but i want it to work also on string is URL hash, so i use


    $(window).load(function () {
        var hash = window.location.hash.substring(1);  // removes the #
        document.getElementById('filter').value = hash; // adds hash string to filter input
    });

but it doesn't filter the list (considering the hash in url already present) even when i make the filter function run on window load (instead of keyup). it just hides all the list items. and i want it to work on window load, not keyup..

any ideas?

回答1:

Simply setting the value of text box alone won't do anything. You need to trigger the function binder to keyup.

$(window).load(function () {
    var hash = window.location.hash.substring(1);  // removes the #
    document.getElementById('filter').value = hash; // adds hash string to filter input
    $('#filter').trigger('keyup'); // trigger a keyup manually
});

Or you could make a general function which accepts the search key and call it with respective values on keyup and window load. Something like

jQuery.expr[':'].containsLower = function(a, i, m) {
  return jQuery(a).text().toUpperCase()
     .indexOf(m[3].toUpperCase()) >= 0;    // for uppercase-lowercase support
};


function displayMatches(value){
  $('ul#myul li').hide().filter(':containsLower("'+value+'")').fadeIn();
}

$('#filter').keyup(function(){
 displayMatches(this.value)
})

$(window).load(function () {
    var hash = window.location.hash.substring(1);  // removes the #
    displayMatches(hash)
});