2012-08-01 88 views
0

我有輸入文本元素,我想要:當我在這個輸入中寫入一些符號時,提醒這個符號, 即如果我寫符號「a」,立即提醒(「a」),如何使這個?我正在嘗試,但它不起作用獲得鍵盤值

$("input").on("keypress", function() { 
       setTimeout (function() {    
        var search_word = $(this).val(); 
        if (search_word.length > 0) { 
         alert(search_word); 
        } 
       },200); 
      }); 

回答

1

您遇到了變量作用域的問題。 this指內部功能..

使用這個代替:

$("input").on("keypress", function() { 
    var that = this; 
    setTimeout (function() {    
     var search_word = $(that).val(); 
     if (search_word.length > 0) { 
      alert(search_word); 
     } 
    },200); 
});​ 

JSFIDDLE

2
$("input").on("keypress", function (e) { 
    alert(String.fromCharCode(e.which)); 
}); 
+0

非常感謝 – 2012-08-01 14:29:47

1

你可以使用KEYUP,在輸入了價值它的發射,這樣就不會需要超時。 http://jsfiddle.net/yF2hU/

$('#foo').bind('keyup', function(e) { 
    alert($(this).val()); 
});​ 
+0

非常感謝 – 2012-08-01 14:33:28