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

时间:2018-10-23 15:45:19

标签: javascript ajax forms turbolinks

我正在通过Turbolinks.visit使用$(document).on("input");操作...

HTML

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

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;
    });  

它工作正常,但是在按住某个键时事件触发了多个请求。

enter image description here

我如何采取预防措施来保持按下状态? .on("input"

2 个答案:

答案 0 :(得分:1)

您是否忘记取消上一个计时器?

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;
});  

编辑:$.debounce()是您要找的东西,而不是重新发明轮子,而是使用现有解决方案始终是一个不错的选择。

答案 1 :(得分:1)

您可能正在寻找https://stackoverflow.com/a/27787793/5523033,因为您正在使用JQuery,因此可以使用$.debounce

下面是一些http://jsfiddle.net/cowboy/cTZJU/的示例

相关问题