Javascript 检查输入是否不正确';t一段时间后变化(稳定)
如果输入稳定,我想触发AJAX请求(为了不在每个新字符之后发送请求)。我尝试了以下方法:Javascript 检查输入是否不正确';t一段时间后变化(稳定),javascript,jquery,Javascript,Jquery,如果输入稳定,我想触发AJAX请求(为了不在每个新字符之后发送请求)。我尝试了以下方法: $('#input').keyup(function(){ // Get the value when keyup is fired value = $('#input').val(); setTimeout(function(){ // If new value after 1 second is the same that the previous value if(
$('#input').keyup(function(){
// Get the value when keyup is fired
value = $('#input').val();
setTimeout(function(){
// If new value after 1 second is the same that the previous value
if( value == $('#input').val() ){
do_stuff();
}
}, 1000); // Wait 1 second to stabilize
});
但我最终得到了一个脚本,它等待1秒的稳定,然后多次而不是仅一次地触发请求
您是否有更好的脚本的想法,或者可能有一个jQuery方法可以做到这一点
谢谢只需将一个变量设置为超时,并在设置新超时之前清除它
$('#input').keyup((function() {
var timeout;
return function(){
if (timeout) {
clearTimeout(timeout);
}
// Get the value when keyup is fired
value = $('#input').val();
timeout = setTimeout(function(){
// If new value after 1 second is the same that the previous value
if( value == $('#value').val() ){
do_stuff();
}
}, 1000); // Wait 1 second to stabilize
};
})());
诀窍是在同时发生更改时取消超时
var timer = null;
$('#input').keyup(function() {
// Get the value when keyup is fired
var value = $('#input').val();
// Reset timeout
clearTimeout(timer);
timer = setTimeout(function() {
// If new value after 1 second is the same that the previous value
if (value === $('#input').val()) {
do_stuff();
}
}, 1000); // Wait 1 second to stabilize
});
如果用户再次输入以下文本,则必须清除超时:
var Timeout; // initialize a variable
$(document).ready(function () {
$('input#input').keypress(function () {
var txtbox = $(this); // copy of this object for further usage
if (Timeout) //check if timeout not null
clearTimeout(Timeout); // not null so clear it
Timeout = setTimeout(function () { // set timeout for 1 second
alert(txtbox.val());
}, 1000);
});
});
我想你的意思是
if(value=$('#input').val())
,而不是$('#value')
原因如下:当用户引入一个新字符(.keyup
激发)时,我会等待一秒钟(setTimeout
)看看文本是否没有变化。如果没有setTimeout
,则do_stuff()代码>函数是在输入不完整的情况下执行的(用户没有完成输入)。是的,我为错误道歉。