如何在按键事件后获得 jQuery .val()? [英] How can I get jQuery .val() AFTER keypress event?

查看:31
本文介绍了如何在按键事件后获得 jQuery .val()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了:

$(someTextInputField).keypress(function() {
  alert($(this).val());
});

现在警报总是返回 keypress 之前的值(例如,字段为空,我输入a",警报给我".然后我输入b",警报给出我'一个'...).但我想要 keypress 之后的值 - 我该怎么做?

Now the alert always returns the value BEFORE the keypress (e.g. the field is empty, I type 'a' and the alert gives me ''. Then I type 'b' and the alert gives me 'a'...). But I want the value AFTER the keypress - how can I do that?

背景:我想在文本字段包含至少一个字符后立即启用按钮.所以我在每个 keypress 事件上运行这个测试,但是使用返回的 val() 结果总是落后一步.使用 change() 事件对我来说不是一个选项,因为在您离开文本框之前,该按钮将被禁用.如果有更好的方法来做到这一点,我很高兴听到它!

Background: I'd like to enable a button as soon as the text field contains at least one character. So I run this test on every keypress event, but using the returned val() the result is always one step behind. Using the change() event is not an option for me because then the button is disabled until you leave the text box. If there's a better way to do that, I'm glad to hear it!

推荐答案

keypress改为keyup:

$(someTextInputField).on("keyup", function() {
  alert($(this).val());
});

keypress 在按键被按下时触发,keyup 在按键被释放时触发.

keypress is fired when the key is pressed down, keyup is fired when the key is released.

这篇关于如何在按键事件后获得 jQuery .val()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆