【问题标题】:Add delay to jQuery AutoComplete为 jQuery 自动完成添加延迟
【发布时间】:2021-04-14 20:22:28
【问题描述】:

有没有办法为我的自动完成搜索功能类型添加延迟?我基本上只希望我的 php 搜索在用户完成输入时启动(延迟 1 秒)。

这是我的 jQuery:

$(document).ready(function(){

  $('.search-box input[type="text"]').on("keyup input", function(){
    /* Get input value on change */
    var inputVal = $(this).val();
    var resultDropdown = $(this).siblings(".result");
    if(inputVal.length > 1){
      $.get("search.php", {term: inputVal}).done(function(data){
        // Display the returned data in browser
        resultDropdown.html(data);
      });
    } else{
      resultDropdown.empty();
    }
  });
  
});

【问题讨论】:

    标签: javascript php jquery mysql


    【解决方案1】:

    您可以尝试使用超时

    $(document).ready(function(){
    
        $('.search-box input[type="text"]').on("keyup input", function(){
          /* Get input value on change */
          var inputVal = $(this).val();
          var resultDropdown = $(this).siblings(".result");
          if(inputVal.length > 1){
            setTimeout(function(){$.get("search.php", {term: inputVal}).done(function(data){
                // Display the returned data in browser
                resultDropdown.html(data);
              });}, 1000);
            } else{
              resultDropdown.empty();
            }
          });
          
        });
    

    【讨论】:

    • 这似乎工作谢谢!然而它并不完美。我的下拉菜单闪烁结果,好像它在超时后迭代每个击键,它发生得非常快,但看起来很丑。有什么想法吗?
    【解决方案2】:
    setTimeout(
      function() 
      {
        //do something special
      }, 5000);
    This should make it work 
    

    如果这对你不起作用,请尝试做

    $(selector).delay(para1, para2);

    【讨论】:

    • 嗨瑞恩,谢谢!也许这可以解决我对 Scais 建议的问题。但我不确定如何使用我正在使用的代码实现您的风格。现在尝试,但没有返回结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 2016-07-08
    • 2018-05-22
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多