当用户在文本框中输入完成时,我想触发一个ajax请求。我不希望它在每次用户键入一封信时运行该函数,因为这会导致大量的ajax请求,但我也不希望他们不得不按回车键。

是否有一种方法,让我可以检测当用户已经完成输入,然后做ajax请求?

在这里使用jQuery !


当前回答

下面是一个解决方案,它在不输入1秒后触发,但在输入为空白时也会立即触发。这在用户删除输入查询后清除搜索结果时非常有用。此解决方案还支持复制和粘贴到搜索框中。$(() =>{…});在简单的Jquery术语中,包装代码的顶部部分仅仅意味着“在页面加载时执行此操作”。

var searchTimer;
var searchInterval = 1000;

$(() => {
    $('#search-box').on('input', (event) => {
        clearTimeout(searchTimer);
        searchTimer = setTimeout(() => {
            searchContacts(event.target.value);
        }, (event.target.value.length > 0) ? searchInterval : 0);
    });
});

function searchContacts(val) {
    console.log('searching: ' + val);
}

其他回答

我觉得解决方案有点简单的输入事件:

var typingTimer;
var doneTypingInterval = 500;

$("#myInput").on("input", function () {
    window.clearTimeout(typingTimer);
    typingTimer = window.setTimeout(doneTyping, doneTypingInterval);
});

function doneTyping () {
    // code here
}

用于将参数与ES6语法一起传递给函数。

$(document).ready(() => {
    let timer = null;
     $('.classSelector').keydown(() => {
     clearTimeout(timer); 
     timer = setTimeout(() => foo('params'), 500);
  });
});

const foo = (params) => {
  console.log(`In foo ${params}`);
}

我不认为keyDown事件在这种情况下是必要的(如果我错了,请告诉我为什么)。在我的(非jquery)脚本类似的解决方案看起来像这样:

var _timer, _timeOut = 2000; 



function _onKeyUp(e) {
    clearTimeout(_timer);
    if (e.keyCode == 13) {      // close on ENTER key
        _onCloseClick();
    } else {                    // send xhr requests
        _timer = window.setTimeout(function() {
            _onInputChange();
        }, _timeOut)
    }

}

这是我在Stack Overflow上的第一个回复,所以我希望有一天这能帮助到别人:)

你们听说过javascript中的闭包吗?!

它非常简单直接,只需将当前输入值与setTimeOut函数关闭的旧值进行比较,瞧,你就完成了。

let timer;
$('#myInput').on('keyup', function() {
  window.clearTimeout(timer);
  // here is the closures javascript magic happens.
  const value = $(this).val();
  timer = setTimeout(() => {
    if(value === $(this).val() && $(this).val()!== ''){
        alert($(this).val());
    }
  }, 500);
})

你可以使用onblur事件来检测文本框何时失去焦点: https://developer.mozilla.org/en/DOM/element.onblur

这与“停止输入”不一样,如果你关心用户输入了一堆东西,然后坐在那里,文本框仍然聚焦。

为此,我建议将setTimeout绑定到onclick事件,并假设在x段时间内没有击键,用户已经停止输入。