2014-07-01 23 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 
});