此函数有效(暂停调用),但搜索值未更新。如果我输入“hello”,则传递给函数 ($(this).val()) 的值是“he”。有没有办法更新它的键值,以便它通过整个搜索?
$('#search').keyup(function () {
if ($(this).val().length > 1) {
var searchthis = $(this).val()
if (srun === 1 && stimer) {
if (stimer) {
window.clearTimeout(stimer)
}
} else {
srun = 1
var stimer = setTimeout(loadsearch(searchthis), 2000)
}
}
})
loadsearch() 将 var srun 设置为 0;
最佳答案
显然,当 srun 未设置时,loadSearch 仅被调用一次。你应该像这样组织你的代码
//put timer outside
var stimer;
$('#search').keyup(function(e) {
if ($(this).val().length <= 1) {
return;
}
var searchthis = $(this).val();
window.clearTimeout(stimer);
stimer = setTimeout(function() {
loadsearch(searchthis);
}, 2000);
});
setTimeout
期望第一个参数是可调用函数,因此 setTimeout(function(){})
如果你输入setTimeout(loadsearch(searchthis))
,它将直接执行loadSearch函数,无需等待2秒。
关于javascript - jquery keyup 延迟有效,但搜索值被 chop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59346980/