当用户在文本框中输入完成时,我想触发一个ajax请求。我不希望它在每次用户键入一封信时运行该函数,因为这会导致大量的ajax请求,但我也不希望他们不得不按回车键。
是否有一种方法,让我可以检测当用户已经完成输入,然后做ajax请求?
在这里使用jQuery !
当用户在文本框中输入完成时,我想触发一个ajax请求。我不希望它在每次用户键入一封信时运行该函数,因为这会导致大量的ajax请求,但我也不希望他们不得不按回车键。
是否有一种方法,让我可以检测当用户已经完成输入,然后做ajax请求?
在这里使用jQuery !
当前回答
用于将参数与ES6语法一起传递给函数。
$(document).ready(() => {
let timer = null;
$('.classSelector').keydown(() => {
clearTimeout(timer);
timer = setTimeout(() => foo('params'), 500);
});
});
const foo = (params) => {
console.log(`In foo ${params}`);
}
其他回答
如果您正在寻找特定的长度(例如邮政编码字段):
$("input").live("keyup", function( event ){
if(this.value.length == this.getAttribute('maxlength')) {
//make ajax request here after.
}
});
所以,我猜完成打字的意思是你停下来一段时间,比如5秒钟。考虑到这一点,让我们在用户释放一个键时启动一个计时器,并在他们按下一个键时清除它。我决定输入问题将是#myInput。
做一些假设…
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 seconds for example
var $input = $('#myInput');
//on keyup, start the countdown
$input.on('keyup', function () {
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$input.on('keydown', function () {
clearTimeout(typingTimer);
});
//user is "finished typing," do something
function doneTyping () {
//do something
}
你可以使用onblur事件来检测文本框何时失去焦点: https://developer.mozilla.org/en/DOM/element.onblur
这与“停止输入”不一样,如果你关心用户输入了一堆东西,然后坐在那里,文本框仍然聚焦。
为此,我建议将setTimeout绑定到onclick事件,并假设在x段时间内没有击键,用户已经停止输入。
我只是想出了一个简单的代码,等待用户完成输入:
步骤1。将超时设置为空,然后在用户输入时清除当前超时。
步骤2。触发keyup事件之前定义的变量的清除超时。
步骤3.为上面声明的变量定义timeout;
<input type="text" id="input" placeholder="please type" style="padding-left:20px;"/>
<div class="data"></div>
javascript代码
var textInput = document.getElementById('input');
var textdata = document.querySelector('.data');
// Init a timeout variable to be used below
var timefired = null;
// Listen for keystroke events
// Init a timeout variable to be used below
var timefired = null;// Listen for keystroke events
textInput.onkeyup = function (event) {
clearTimeout(timefired);
timefired = setTimeout(function () {
textdata.innerHTML = 'Input Value:'+ textInput.value;
}, 600);
};
很晚的答案,但我添加它是因为现在是2019年,这完全可以用漂亮的ES6实现,没有第三方库,而且我发现大多数高评分的答案都很笨重,有太多变量。
优雅的解决方案从这篇优秀的博客文章。
function debounce(callback, wait) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(function () { callback.apply(this, args); }, wait);
};
}
window.addEventListener('keyup', debounce( () => {
// code you would like to run 1000ms after the keyup event has stopped firing
// further keyup events reset the timer, as expected
}, 1000))