当用户在文本框中输入完成时,我想触发一个ajax请求。我不希望它在每次用户键入一封信时运行该函数,因为这会导致大量的ajax请求,但我也不希望他们不得不按回车键。
是否有一种方法,让我可以检测当用户已经完成输入,然后做ajax请求?
在这里使用jQuery !
当用户在文本框中输入完成时,我想触发一个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);
})
其他回答
每个页面有多个计时器
所有其他答案只适用于一个控制(包括我的另一个答案)。 如果每个页面有多个控件(例如在购物车中),只有用户输入内容的最后一个控件才会被调用。在我的情况下,这当然不是希望的行为-每个控件应该有自己的计时器。
要解决这个问题,你只需要向函数传递一个ID,并维护一个timeoutHandles字典,如下所示:
函数声明:
var delayUserInput = (function () {
var timeoutHandles = {};
return function (id, callback, ms) {
if (timeoutHandles[id]) {
clearTimeout(timeoutHandles[id]);
}
timeoutHandles[id] = setTimeout(callback, ms);
};
})();
功能用途:
delayUserInput('yourID', function () {
//do some stuff
}, 1000);
它只是一行下划线。js debounce函数:
$('#my-input-box').keyup(_.debounce(doSomething , 500));
这基本上是在我停止输入500毫秒后做某事。
欲了解更多信息:http://underscorejs.org/#debounce
前两个答案都不适合我。所以,这是我的解决方案:
var timeout = null;
$('#myInput').keyup(function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
//do stuff here
}, 500);
});
哇,甚至有3条评论都是正确的!
Empty input is not a reason to skip function call, e.g. I remove waste parameter from url before redirect .on ('input', function() { ... }); should be used to trigger keyup, paste and change events definitely .val() or .value must be used You can use $(this) inside event function instead of #id to work with multiple inputs (my decision) I use anonymous function instead of doneTyping in setTimeout to easily access $(this) from n.4, but you need to save it first like var $currentInput = $(this);
编辑我看到有些人不理解没有复制粘贴就绪代码的指示。在这里你
var typingTimer;
// 2
$("#myinput").on('input', function () {
// 4 3
var input = $(this).val();
clearTimeout(typingTimer);
// 5
typingTimer = setTimeout(function() {
// do something with input
alert(input);
}, 5000);
});
一旦你检测到文本框的焦点,在键上做一个超时检查,并重置它每次触发。
当超时结束时,执行ajax请求。