jQuery Javascript - 在每次按键时从文本框中获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18207996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript - get value from textbox at every keypress
提问by user2450099
I have a textbox and I want to use the data in it every time something is entered; letter by letter.
我有一个文本框,每次输入内容时我都想使用其中的数据;逐个字母。
What is happening is that when a value is entered, the Javascript is being executed beforethe value is actually put into the textbox, meaning that it always lags one character behind.
发生的情况是,当输入一个值时,Javascript 会在该值实际放入文本框之前执行,这意味着它总是落后一个字符。
$(document).ready(
function() {
$('#test').keypress(
function() {
var value = document.getElementById('test').value;
alert(value);
});
})
<input id="test" type="text" />
Here's whats happening:
这是发生了什么:
input alert
w ""
e "w"
a "we"
l "wea"
t "weal"
h "wealt"
Whereas I want it to happen dynamically; i.e. when I enter "w" I want the alert to contain "w" immediately after.
而我希望它动态发生;即当我输入“w”时,我希望警报立即包含“w”。
回答by dxh
keypresshappens before the change, yes. keyuphappens after. Listen to that instead.
keypress发生在更改之前,是的。keyup之后发生。听那个。
回答by Sergio
You should try keyupevent, because keypresshappens before symbol is being input in a textbox
您应该尝试keyup事件,因为keypress在文本框中输入符号之前发生
回答by Arun P Johny
use keyup
使用键盘
$(document).ready(
function() {
$('#test').keyup(
function() {
var value = document.getElementById('test').value;
alert(value);
});
})
回答by John Dorean
回答by Vishal
use keyup instead that will work
使用 keyup 代替它会起作用
$(document).ready(
function() {
$('#test').keyup(
function() {
var value = document.getElementById('test').value;
alert(value);
});
})
回答by Nicolae Olariu
回答by Raoul George
回答by IsisCode
Use keyupinstead, take a look at this:
使用keyup替代,看看这个:

