简体   繁体   English

如何禁用JavaScript搜索自动完成功能上的多个请求?

[英]How to disable multiple request on the javascript search autocomplete?

I am using Turbolinks.visit action, via $(document).on("input"); 我通过$(document).on("input");使用Turbolinks.visit动作$(document).on("input"); ... ...

Html HTML

<form id="mainSearch" method="get" autocomplete="off">
    <input type="search" name="s" placeholder="Search" />
</form>

Javascript 使用Javascript

$(document).off().on("input", "#mainSearch", function(e) {

        e.stopImmediatePropagation();
        e.stopPropagation();
        e.preventDefault();

        var ser     = $(this).serialize();

        setTimeout(function(){
            Turbolinks.visit(
                homeurl+"/?"+ser,
                {
                    change: ['content']
                }
            );
        },110);

        return false;
    });  

It is working right but event fired multiple request when hold down a key. 它工作正常,但是在按住某个键时事件触发了多个请求。

在此处输入图片说明

do how I take precautions to keep it pressed? 如何采取预防措施使其保持按下状态? .on("input"

Did you forget to cancel the previous timer? 您是否忘记取消上一个计时器?

var timer = null;

$(document).off().on("input", "#mainSearch", function(e) {

    e.stopImmediatePropagation();
    e.stopPropagation();
    e.preventDefault();

    var ser= $(this).serialize();

    clearInterval(timer);

    timer = setTimeout(function(){
        Turbolinks.visit(
            homeurl+"/?"+ser,
            {
                change: ['content']
            }
        );
    },110);

    return false;
});  

Edit: Instead of re-inventing the wheel it's always a good choice to use existing solutions, $.debounce() is what you are looking for. 编辑: $.debounce()您要重新发明轮子,而是使用现有解决方案始终是一个不错的选择。

You might be looking for https://stackoverflow.com/a/27787793/5523033 since you're using JQuery you can use $.debounce 您可能正在寻找https://stackoverflow.com/a/27787793/5523033,因为您使用的是JQuery,因此可以使用$.debounce

and here's a few examples to play around with http://jsfiddle.net/cowboy/cTZJU/ 这是与http://jsfiddle.net/cowboy/cTZJU/一起使用的一些示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM