2009-11-04 22 views
1

我試圖捕獲用戶輸入使用jquery和keydown事件。使用jquery的文本框文本捕獲總是'後面的一個字符'

這裏是我的代碼:

$(document).ready(function() { 
     $("#searchText").keydown(function() { 
      var filter = jQuery.trim($(this).val()); 
      if (filter.length > 3 || filter.length == 0) { 
       //hit the index action again and pass the keyword 
       $("#results").fadeOut("fast"); 
       $("#results").load("/Organisation/Index?keyword=" + filter, null, function() { 
        $(this).fadeIn("fast"); 
       }); 
      } 
     }); 
    }); 

這是一個事實,即始終捕捉到的字符串似乎是「過時的」一個字符工作,除了莫,我必須按其他鍵實際上得到我想要傳遞給我的動作的文本。

在此先感謝!

+0

你想捕捉整個輸入,或只是每個字符的用戶類型? – TStamper 2009-11-04 20:44:14

+3

請嘗試'keyup'。 – 2009-11-04 20:46:36

回答

8

你的問題是'keydown'事件。由於當按下鍵時,該值的處理完成,新按下的字符尚未計入輸入。通過使用'keyup',處理在新按下的字符已被添加到值之後完成。

$(document).ready(function() { 
     $("#searchText").keyup(function() { 
      var filter = jQuery.trim($(this).val()); 
      if (filter.length < 3 || filter.length == 0) { 
       //hit the index action again and pass the keyword 
       $("#results").fadeOut("fast"); 
       $("#results").load("/Organisation/Index?keyword=" + filter, null, function() { 
        $(this).fadeIn("fast"); 
       }); 
      } 
     }); 
    });
0

您也可以嘗試使用綁定方法捕捉其他「鍵擊」事件,就像這樣:

$("#searchText").bind("keyup click blur focus change paste", function(){ 
    //stuff 
}); 
相關問題