当用户在文本框中输入完成时,我想触发一个ajax请求。我不希望它在每次用户键入一封信时运行该函数,因为这会导致大量的ajax请求,但我也不希望他们不得不按回车键。
是否有一种方法,让我可以检测当用户已经完成输入,然后做ajax请求?
在这里使用jQuery !
当用户在文本框中输入完成时,我想触发一个ajax请求。我不希望它在每次用户键入一封信时运行该函数,因为这会导致大量的ajax请求,但我也不希望他们不得不按回车键。
是否有一种方法,让我可以检测当用户已经完成输入,然后做ajax请求?
在这里使用jQuery !
当前回答
不是一个直接的答案,但如果有人在寻找AngularJS的解决方案。我根据这里流行的解决方案写了一个指令。
app.directive("ngTypeEnds", ["$timeout", function ($timeout) {
return function (scope, element, attrs) {
var typingTimer;
element.bind("keyup", function (event) {
if (typingTimer)
$timeout.cancel(typingTimer);
if (angular.element(element)[0].value) {
typingTimer = $timeout(function () {
scope.$apply(function () {
scope.$eval(attrs.ngTypeEnds);
});
}, 500);
}
event.preventDefault();
});
};
}]);
其他回答
如果有必要让用户离开字段,我们可以使用“onBlur”而不是Javascript中的Onchange
<TextField id="outlined-basic" variant="outlined" defaultValue={CardValue} onBlur={cardTitleFn} />
如果这是不必要的设置定时器将是一个很好的选择。
为什么不直接使用onfocusout?
https://www.w3schools.com/jsreF/event_onfocusout.asp
如果它是一个表单,它们将始终保留每个输入字段的焦点,以便单击提交按钮,这样您就知道没有输入会错过调用其onfocusout事件处理程序。
哇,甚至有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);
});
你可以使用onblur事件来检测文本框何时失去焦点: https://developer.mozilla.org/en/DOM/element.onblur
这与“停止输入”不一样,如果你关心用户输入了一堆东西,然后坐在那里,文本框仍然聚焦。
为此,我建议将setTimeout绑定到onclick事件,并假设在x段时间内没有击键,用户已经停止输入。
var timer;
var timeout = 1000;
$('#in').keyup(function(){
clearTimeout(timer);
if ($('#in').val) {
timer = setTimeout(function(){
//do stuff here e.g ajax call etc....
var v = $("#in").val();
$("#out").html(v);
}, timeout);
}
});
完整的例子:http://jsfiddle.net/ZYXp4/8/