【问题标题】:jQuery check on wordchange rather than "change" triggerjQuery 检查 wordchange 而不是“更改”触发器
【发布时间】:2011-01-10 17:28:55
【问题描述】:

我有一个用户输入搜索参数的输入,目前我在 keyup 上有它对返回搜索结果的 PHP 脚本执行 POST ajax 请求。然而,它在大约 10 秒内(当用户键入时)触发了 500 亿个(不是字面意思)发布请求,这减慢了整个体验。我可以使用jQuery通过检测空格键的使用来检测“wordup”而不是“keyup”吗?

这有意义吗?

【问题讨论】:

    标签: jquery ajax keyboard onkeyup


    【解决方案1】:

    我将此作为单独的答案添加,因为它与我的第一个答案完全不同。

    $('#yourinput').keyup(function(){
        var input = this,
            timer = $.data(this, 'timer'),
            lastrequest = $.data(this, 'lastrequest');
    
        if (timer) { // if there is a keyup timeout still pending, cancel it
            clearTimeout(timer);
            $.data(this, 'timer', 0);
        }
    
        if (lastrequest) { // if there is an AJAX request still running, abort it
            lastrequest.abort();
            $.data(this, 'lastrequest', false);
        }
    
        timer = setTimeout(function(){
            lastrequest = $.post({ // or whatever your AJAX call is...
                url: 'yourfile',
                data: { search: input.value },
                success: function(response){
                    lastrequest = false;
                    // handle response here
                }
            });
            $.data(input, 'lastrequest', lastrequest);
        }, 500);
        $.data(this, 'timer', timer);
    });
    

    【讨论】:

    • 这个我会投票。但如果你愿意,可以叫我.data() 瘾君子,但你可以使用那个方便的函数而不是创建全局变量。感谢.abort - 没想到。
    • 我试着写这样的东西,但你也打败了我:这是一个小提琴jsfiddle.net/k7R57
    • @German 好电话$.data;我已经添加了它。有点笨重,但你去...
    【解决方案2】:
    $('#yourinput').keyup(function(e) {
        if (e.which == 32) { // space key pressed
            // do your AJAX here
        }
    });
    

    有关此功能的更多信息,请参阅event.which

    【讨论】:

    • 不会因为一个单词而触发
    • @German:它确实回答了这个问题,无论 OPs 建议的解决方案多么可怕。
    • 是的,没错——我需要单字搜索!不过好主意
    • @benhowdle89 这是你的主意! :-)
    • @benhowdle89 查看我的其他答案 :-)
    【解决方案3】:

    你当然可以;您在本地检测 keyup 事件并检查它们是否有空间。

    但是,如果您能够设法获取与前缀匹配的所有搜索结果并将它们发送到数据结构中的 javascript,您将获得更多的优势。查看“数字搜索树”(也称为“尝试”)了解详细信息。

    【讨论】:

      【解决方案4】:

      当用户在特定时间段内停止输入时,您可以使用延迟之类的方法吗?

      也许是这样的?您也可以添加附加功能来触发空格键按下。 (这仅用于 Google 风格的 insta 搜索,因此它可能/可能没有帮助)。

      $('#Search').keyup(function (event) 
              {
                  delay(function(){
      
                  var textboxValue = $('#Search').val();
      
                  if( textboxValue.length >= 2)
                  {
                    //Perform search
                  }
      
              });
      });
      
      var delay = (function(){
      var timer = 0;
          return function(callback, ms){
          clearTimeout (timer);
          timer = setTimeout(callback, ms);
      };
      })();
      

      【讨论】:

        猜你喜欢
        • 2016-07-20
        • 2021-08-12
        • 2017-10-06
        • 1970-01-01
        • 2013-05-30
        • 1970-01-01
        • 2021-03-22
        • 1970-01-01
        • 2016-11-18
        相关资源
        最近更新 更多