jquery keypress() 事件获取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1411557/
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
jquery keypress() event get text
提问by Fiona - myaccessible.website
I want a function to be run when a keypress occurs on a text box, so I have this code:
我希望在文本框上发生按键时运行一个函数,所以我有以下代码:
$("input[x]").keypress(function() {
DoX();
})
This is working fine, but in my function I want to do something based on the text value in the textbox
这工作正常,但在我的函数中,我想根据文本框中的文本值做一些事情
var textValue = ("input[x]").val();
Now the problem here is that it lags behind by a key so if my text box says 'He' and I type an 'l', then I want my textValue to be 'Hel', but it is returning the previous value 'He' because presumably the character hasn't been put in the text box yet.
现在这里的问题是它落后于一个键,所以如果我的文本框显示“He”并且我输入了一个“l”,那么我希望我的 textValue 是“Hel”,但它返回的是先前的值“He”因为大概这个字符还没有被放入文本框中。
Is there a way of getting 'Hel' out of my function here?
有没有办法让“Hel”脱离我的功能?
Thanks :)
谢谢 :)
回答by CMS
You can try to use the keyup event:
您可以尝试使用 keyup 事件:
$(selector).keyup(function() {
var textValue = $(this).val();
DoX();
});
回答by Vincent Ramdhanie
if you are stuck using the keypressed for some other reason (so you cannot change to keyup as suggested) then you can get the last character typed like this:
如果您由于其他原因无法使用按键(因此您无法按照建议更改为 keyup),那么您可以像这样输入最后一个字符:
$("input[x]").keypress(function (e) {
var c = String.fromCharCode(e.which);
//process the single character or
var textValue = $("input[x]").val();
var fulltext = textValue + c;
//process the full text
});
回答by zzandy
Use onkeyup
, it will show the right value.
使用onkeyup
,它将显示正确的值。
回答by Semra
Use setTimeout without a delay. It will run immediately after keypress event completes so you'll have the correct value of the input.
立即使用 setTimeout。它会在按键事件完成后立即运行,因此您将获得正确的输入值。
$("input[x]").keypress(function() {
setTimeout(DoX);
});