2014-07-01 22 views
0

如果输入稳定(为了在每个新字符后不发送请求),我想发起一个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(value == $('#input').val()){ 
     do_stuff(); 
    } 

    }, 1000); // Wait 1 second to stabilize 

}); 

但我结束了与等待1秒的稳定,发射请求很多次,而不是只有一次的脚本。

你有一个更好的脚本的想法,或者有一个jQuery的方法可以做到这一点吗?

感谢

+0

我想你的意思是'如果(价值== $( '#输入')。 val())而不是'$('#value')' – Blazemonger

+0

这是为什么:当用户引入一个新字符('.keyup')时,我等待一秒钟('setTimeout'),看看文本不会改变。如果没有'setTimeout','do_stuff();'函数会以不完整的输入执行(用户没有完成输入)。 – htaidirt

+0

是的,我对这个错误表示歉意。 – htaidirt

回答

1

你要清楚,如果超时用户再次输入一些文字是这样的:

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); 
    }); 
}); 

FIDDLE DEMO

0

正好被设置为超时变量并设置新的超时

$('#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 

}; 
})()); 
1

的诀窍是什么时,在此期间变更取消超时之前清除它。

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 
});