在 window.onload 中调用函数不起作用

Calling a function in window.onload does not work

背景

我有一个带有搜索文本框和转发器的简单应用程序。 当用户在搜索文本框中输入文本时,列表会根据输入的文本进行过滤。这是工作正常的 javascript 代码:

<script type="text/javascript">
    $(document).ready(function(){
        $('input').keyup(function(){
            localStorage.setItem("filterString", this.value);
            filter(this);
        });
    });

    function filter(element) {
        var value = $(element).val().toLowerCase();

        $(".panel").each(function () {
            if ($(this).text().toLowerCase().indexOf(value) > -1) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    }
</script>  

我想做什么

我希望应用程序在用户返回此页面时保留筛选列表。

我尝试采用的方法是使用 localStorage 存储搜索字符串: localStorage.setItem("filterString", this.value);"

然后当 window.onload 被调用时,我检索 filterString,呈现搜索文本框,并调用过滤器函数。

问题和我尝试过的方法

这是我试过的代码:

window.onload = function()
{
    if(typeof(Storage) !== "undefined")
    {
         var filterString = localStorage.getItem("filterString");
         txtSearch.value = filterString;
         filter(filterString);
    }
 }

过滤器在 keyup 上仍然可以正常工作,但在 onload 上不起作用。

我也试过:

$(document).ready(function(){
    $('input').keyup(function () {
        localStorage.setItem("filterString", this.value);
        filter(this);
    });
    //Added this
    filter(localStorage.getItem("filterString"));
});

这仍然不起作用,如果我这样做,keyup 上的过滤器将停止工作。

为什么我不能调用 filter 函数?

如有任何建议,我们将不胜感激。

问题是您试图通过将字符串作为参数传递来调用 filter 函数,它希望您传递 element.

因此,您应该将最后的代码更改为:

$(document).ready(function(){
  $('input').keyup(function () {
    localStorage.setItem("filterString", this.value);
    filter(this);
  });
  // Change the input value to the localStorage value
  $('input').val(localStorage.getItem("filterString"));
  // And then, send the element to the filter
  filter($('input')[0]); ;
});

只需在 document.ready 函数中添加以下内容即可。记得在你现有的函数之后调用它。

 $('input').keyup();

像这样

   $(document).ready(function(){
    $('input').keyup(function(){
        localStorage.setItem("filterString", this.value);
        filter(this);
    });
   $('input').keyup(); //added here ,after your keyup function
});