当用户在文本框中输入完成时,我想触发一个ajax请求。我不希望它在每次用户键入一封信时运行该函数,因为这会导致大量的ajax请求,但我也不希望他们不得不按回车键。
是否有一种方法,让我可以检测当用户已经完成输入,然后做ajax请求?
在这里使用jQuery !
当用户在文本框中输入完成时,我想触发一个ajax请求。我不希望它在每次用户键入一封信时运行该函数,因为这会导致大量的ajax请求,但我也不希望他们不得不按回车键。
是否有一种方法,让我可以检测当用户已经完成输入,然后做ajax请求?
在这里使用jQuery !
当前回答
如果有必要让用户离开字段,我们可以使用“onBlur”而不是Javascript中的Onchange
<TextField id="outlined-basic" variant="outlined" defaultValue={CardValue} onBlur={cardTitleFn} />
如果这是不必要的设置定时器将是一个很好的选择。
其他回答
我觉得解决方案有点简单的输入事件:
var typingTimer;
var doneTypingInterval = 500;
$("#myInput").on("input", function () {
window.clearTimeout(typingTimer);
typingTimer = window.setTimeout(doneTyping, doneTypingInterval);
});
function doneTyping () {
// code here
}
如果你需要等待,直到用户完成输入使用简单的这个:
$(document).on('change','#PageSize', function () {
//Do something after new value in #PageSize
});
使用ajax调用的完整示例-这适用于我的寻呼机-每个列表的项目计数:
$(document).ready(function () {
$(document).on('change','#PageSize', function (e) {
e.preventDefault();
var page = 1;
var pagesize = $("#PageSize").val();
var q = $("#q").val();
$.ajax({
url: '@Url.Action("IndexAjax", "Materials", new { Area = "TenantManage" })',
data: { q: q, pagesize: pagesize, page: page },
type: 'post',
datatype: "json",
success: function (data) {
$('#tablecontainer').html(data);
// toastr.success('Pager has been changed', "Success!");
},
error: function (jqXHR, exception) {
ShowErrorMessage(jqXHR, exception);
}
});
});
});
如果您正在寻找特定的长度(例如邮政编码字段):
$("input").live("keyup", function( event ){
if(this.value.length == this.getAttribute('maxlength')) {
//make ajax request here after.
}
});
用于将参数与ES6语法一起传递给函数。
$(document).ready(() => {
let timer = null;
$('.classSelector').keydown(() => {
clearTimeout(timer);
timer = setTimeout(() => foo('params'), 500);
});
});
const foo = (params) => {
console.log(`In foo ${params}`);
}
不是一个直接的答案,但如果有人在寻找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();
});
};
}]);