背景
我有一个带有搜索文本框和中继器的简单应用程序。 当用户在搜索文本框中输入文本时,列表将按输入的文本进行过滤。这是运行良好的 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
函数,并且它希望您传递元素
。
因此,您应该将最后的代码更改为:
$(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]); ;
});
关于javascript - 在window.onload中调用函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32617926/