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

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

在这里使用jQuery !


当前回答

不确定我的需求是不是有点奇怪,但我需要类似于这个的东西,这就是我最终使用的:

$('input.update').bind('sync', function() {
    clearTimeout($(this).data('timer'));            
    $.post($(this).attr('data-url'), {value: $(this).val()}, function(x) {
        if(x.success != true) {
            triggerError(x.message);    
        }
    }, 'json');
}).keyup(function() {
    clearTimeout($(this).data('timer'));
    var val = $.trim($(this).val());
    if(val) {
        var $this = $(this);
        var timer = setTimeout(function() {
            $this.trigger('sync');
        }, 2000);
        $(this).data('timer', timer);
    }
}).blur(function() {
    clearTimeout($(this).data('timer'));     
    $(this).trigger('sync');
});

这允许我在我的应用程序中有这样的元素:

<input type="text" data-url="/controller/action/" class="update">

当用户“完成输入”(2秒内没有动作)或转到另一个字段(模糊出元素)时更新

其他回答

为什么不直接使用onfocusout?

https://www.w3schools.com/jsreF/event_onfocusout.asp

如果它是一个表单,它们将始终保留每个输入字段的焦点,以便单击提交按钮,这样您就知道没有输入会错过调用其onfocusout事件处理程序。

const inText = document.getElementById('inText') const outText = document.getElementById('outText') Const delay = 1000 让计时器 inText。addEventListener('input', code => { clearTimeout(计时器); timer = setTimeout(x => { outText。innerHTML = inText.value },延迟,代码) }) <textarea id='inText'>编辑这个和 <pre id='outText'>在你停止输入一秒钟后看到结果</pre>

我需要为特定的控制运行我的程序,这对我来说很有效:

function debounce(func, timeout) {
            let timer;
            return (...args) => {
                clearTimeout(timer);
                timer = setTimeout(() => { func.apply(this, args); }, timeout);
            };
        }

$('#txtFilterClientCode').keyup(debounce(function () {
            console.log("Test");
        }, 1000));

对于alpine.js用户<input @input.debounce.500ms="fn()" >

很晚的答案,但我添加它是因为现在是2019年,这完全可以用漂亮的ES6实现,没有第三方库,而且我发现大多数高评分的答案都很笨重,有太多变量。

优雅的解决方案从这篇优秀的博客文章。

function debounce(callback, wait) {
  let timeout;
  return (...args) => {
      clearTimeout(timeout);
      timeout = setTimeout(function () { callback.apply(this, args); }, wait);
  };
}

window.addEventListener('keyup', debounce( () => {
    // code you would like to run 1000ms after the keyup event has stopped firing
    // further keyup events reset the timer, as expected
}, 1000))