我有一个在按键事件之后执行的函数:
$("#txtarea").keypress(function(){
alert(document.getElementById("txtarea").value);
});
我希望在每次按键后都能返回文本区域的新文本,以便可以在其他JavaScript函数中同时使用。但是这段代码存在的问题是,一旦按下键盘,该函数就会显示一个空字符串。谢谢您的帮助。
我有一个在按键事件之后执行的函数:
$("#txtarea").keypress(function(){
alert(document.getElementById("txtarea").value);
});
尽量使用keyup
而不是keypress
您可以使用此代码,注意使用keyup而不是keypress,因为这意味着已将按键添加到文本区域中:
$('#txtarea').keyup(function() {
alert(this.value);
});
$('#txtarea').keypress(function(event) {
return false; // this will disable the new value assignment
});
使用 event.which 可以找出被点击的按钮并进行操作。
示例:
<input id="txtarea" />
$('#txtarea').keypress(function(e){
var value = this.value;
alert(value);
alert(value + String.fromCharCode(e.which))
});
你也可以使用keyup
事件,但它与keypress
的含义和用法不同。
请注意!
在零长度超时后执行行为。
$("#txtarea").keypress(function(){
setTimeout(function () {
alert(document.getElementById("txtarea").value);
}, 0);
});