jQuery检查wordchange而不是"更改"触发器

ben*_*e89 0 keyboard ajax jquery onkeyup

我有一个输入,用户输入一个搜索参数,目前我在keyup上有一个POST ajax请求到一个返回搜索结果的PHP脚本.然而,它在大约10秒内(如用户输入的那样)发出500亿(不是字面意思)的发布请求,这会减慢整个体验.我可以通过检测空格键的使用来使用jQuery来检测"wordup"而不是"keyup"吗?

这有意义吗?

lon*_*day 5

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

$('#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);
});
Run Code Online (Sandbox Code Playgroud)