Filter list based on URL hash string

◇◆丶佛笑我妖孽 提交于 2019-12-25 02:29:43

问题


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)
});


来源:https://stackoverflow.com/questions/24466096/filter-list-based-on-url-hash-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!