当用户在文本框中输入完成时,我想触发一个ajax请求。我不希望它在每次用户键入一封信时运行该函数,因为这会导致大量的ajax请求,但我也不希望他们不得不按回车键。
是否有一种方法,让我可以检测当用户已经完成输入,然后做ajax请求?
在这里使用jQuery !
当用户在文本框中输入完成时,我想触发一个ajax请求。我不希望它在每次用户键入一封信时运行该函数,因为这会导致大量的ajax请求,但我也不希望他们不得不按回车键。
是否有一种方法,让我可以检测当用户已经完成输入,然后做ajax请求?
在这里使用jQuery !
当前回答
前两个答案都不适合我。所以,这是我的解决方案:
var timeout = null;
$('#myInput').keyup(function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
//do stuff here
}, 500);
});
其他回答
你们听说过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);
})
声明以下延迟函数:
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})()
然后使用它:
let $filter = $('#item-filter');
$filter.on('keydown', function () {
delay(function () {
console.log('this will hit, once user has not typed for 1 second');
}, 1000);
});
我需要为特定的控制运行我的程序,这对我来说很有效:
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));
我不认为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上的第一个回复,所以我希望有一天这能帮助到别人:)
上面选择的答案不成立。
因为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,将箭头函数替换为常规函数。