2015-02-09 49 views
-3

我寫下面的代碼來檢索用戶輸入時使用ajax的建議。問題是調用可能太多,所以我使用setTimeout。我的流程是否正確完成?建議列表捕捉用戶輸入延遲

$('.text').on('keydown', function(e) { 
        if ($(this).val().length >= 3) { 

         var suggestionURL = "example.com?q" 
         + $(this).val(); 
         setTimeout(function(){ 
          show_suggestion(); 
         }, 1000); 

         function show_suggestion(){ 

          // $.ajax.. 
         } 
        } 
       }); 
+0

_'Is我的流程做得正確? '_ - 它工作嗎?那麼它可能是正確的。 – 2015-02-09 02:21:19

+0

你的問題措辭不佳,但我相信你要找的是AJAX debounce。 Underscore有這樣的幫手:http://underscorejs.org/#debounce。 – Eclecticist 2015-02-09 02:24:32

回答

0

您可以使用此setTimeout()clearTimeout()。這將確保該功能僅被稱爲用戶輸入了3個以上字符並且至少停止鍵入半秒鐘。根據需要調整時間:

$(function() { 
 
    var timeOut = 0; 
 
    $(".text") 
 
     .keyup(function() { 
 
     // check input has at least 4 chars 
 
     if ($(this).val().length >= 3) { 
 
      
 
     // cancel looking, the user typed another character 
 
     clearTimeout(timeOut); 
 
     // set a timeout 
 
     // if user doesn't type another key 
 
     // within half a second the function is called 
 
\t \t timeOut = setTimeout(function() { 
 
\t \t \t show_suggestion(); 
 
\t \t }, 500); // change time as needed 
 
      
 
     } 
 
    }); 
 

 
}); 
 

 
function show_suggestion(){ 
 
    alert('user stopped typing, call the ajax'); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" class="text"/><br><br> 
 
<input type="text" class="text"/><br><br> 
 
<input type="text" class="text"/><br><br> 
 
<input type="text" class="text"/><br><br>

+0

當用戶點擊backspace時,keyup無法捕捉到。爲什麼? – Fernandez 2015-02-09 02:40:16

+0

如果箱子裏少於3個字符,如果箱子裏有4個字符並且退格,它應該可以工作,如果你有三個或更少的退格但它不會被調用 – DelightedD0D 2015-02-09 02:43:14