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

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

在这里使用jQuery !


当前回答

你们听说过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);
})

其他回答

我不认为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上的第一个回复,所以我希望有一天这能帮助到别人:)

如果您正在寻找特定的长度(例如邮政编码字段):

$("input").live("keyup", function( event ){
if(this.value.length == this.getAttribute('maxlength')) {
        //make ajax request here after.
    }
  });

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

上面选择的答案不成立。

因为typingTimer偶尔会设置多次(对于快速键入者,按下键之前按下键两次),那么它就不能正确清除。

下面的解决方案解决了这个问题,并将在完成OP请求后调用X秒。它也不再需要冗余的keydown函数。我还添加了一个检查,这样如果输入为空,函数调用就不会发生。

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms (5 seconds)

//on keyup, start the countdown
$('#myInput').keyup(function(){
    clearTimeout(typingTimer);
    if ($('#myInput').val()) {
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
});

//user is "finished typing," do something
function doneTyping () {
    //do something
}

和相同的代码在普通JavaScript解决方案:

//setup before functions
let typingTimer;                //timer identifier
let doneTypingInterval = 5000;  //time in ms (5 seconds)
let myInput = document.getElementById('myInput');

//on keyup, start the countdown
myInput.addEventListener('keyup', () => {
    clearTimeout(typingTimer);
    if (myInput.value) {
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
});

//user is "finished typing," do something
function doneTyping () {
    //do something
}

这个解决方案确实使用了ES6,但在这里没有必要。只需将let替换为var,将箭头函数替换为常规函数。

如果有必要让用户离开字段,我们可以使用“onBlur”而不是Javascript中的Onchange

  <TextField id="outlined-basic"  variant="outlined" defaultValue={CardValue} onBlur={cardTitleFn} />

如果这是不必要的设置定时器将是一个很好的选择。