You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery中keyup事件绑定setTimeout延迟执行不生效问题求解

问题原因

你修改后的代码中setTimeout的第一个参数直接写了search(true, searchword),这会立即执行search函数,而不是把函数作为引用传给setTimeout延迟调用,所以防抖逻辑直接失效。

修复方法

你只需要把setTimeout里的执行逻辑包裹成匿名函数即可,同时建议给searchword变量加上声明避免污染全局作用域,修复后的完整代码如下:

$('.search-word').keyup(function(e) {
    // 加变量声明,避免全局污染
    const searchword = $(this).val();
    clearTimeout($.data(this, 'timer'));
    if (e.keyCode == 13){
        search(true, searchword);
    }else{
        // 把调用逻辑包裹在匿名函数里,延迟到定时器触发时再执行
        $(this).data('timer', setTimeout(function() {
            search(false, searchword)
        }, 500));
    }
});

function search(force, searchword) {
  const zoekwaarde = searchword;
  const account_id = $("#account_id").val();
  $.ajax({
     type:'post',
     url:"includes/searchaddress.php",
     data:{zoekwaarde: zoekwaarde, account_id: account_id},
     success:function(data){
         $( "#adressenlist" ).show().empty().append( data );
         $( "#deleteresult" ).hide();
         $( "#adresresult" ).hide();
     }
 });
}

你也可以用bind方法绑定参数实现同样效果:

$(this).data('timer', setTimeout(search.bind(null, false, searchword), 500));

额外优化建议

  • 如果两个输入框需要对应不同的搜索结果区域,不要共用同一个#adressenlist渲染结果,建议通过父表单的自定义属性关联对应结果容器的ID,实现输入框和结果区的一一绑定。
  • 如果两个表单的account_id不同,不要共用同一个#account_id的id选择器取值,应该从当前触发事件的输入框所在表单内查找对应的隐藏域,避免取值错误:
// 放到keyup事件回调内
const account_id = $(this).closest('.search-address').find('input[name="account_id"]').val();

内容的提问来源于stack exchange,提问作者twan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 15:15:04