Javascript 在window.onload中调用函数无效 背景
我有一个带有搜索文本框和转发器的简单应用程序。 当用户在搜索文本框中输入文本时,列表将根据输入的文本进行过滤。下面是运行良好的javascript代码:Javascript 在window.onload中调用函数无效 背景,javascript,asp.net,webforms,Javascript,Asp.net,Webforms,我有一个带有搜索文本框和转发器的简单应用程序。 当用户在搜索文本框中输入文本时,列表将根据输入的文本进行过滤。下面是运行良好的javascript代码: <script type="text/javascript"> $(document).ready(function(){ $('input').keyup(function(){ localStorage.setItem("filterString", this.value);
<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>
过滤器在keyup
上仍能正常工作,但在onload
上不起作用
我也试过:
$(document).ready(function(){
$('input').keyup(function () {
localStorage.setItem("filterString", this.value);
filter(this);
});
//Added this
filter(localStorage.getItem("filterString"));
});
这仍然不起作用,如果我这样做,keyup
上的过滤器将停止工作
为什么我不能调用过滤器函数
任何建议都将不胜感激 问题在于,您试图通过将字符串作为参数传递来调用过滤器
函数,它希望您传递元素
因此,您应该将上一个代码更改为:
$(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
});
我猜-您正在存储此.value,而您将需要筛选函数中的元素。。尝试更改函数以接受输入值作为参数并传递该值。。
$(document).ready(function(){
$('input').keyup(function(){
localStorage.setItem("filterString", this.value);
filter(this);
});
$('input').keyup(); //added here ,after your keyup function
});