Fio*_*ite 28 jquery textbox keypress
我希望在文本框上发生按键时运行一个函数,所以我有这个代码:
$("input[x]").keypress(function() {
DoX();
})
Run Code Online (Sandbox Code Playgroud)
这工作正常,但在我的函数中,我想根据文本框中的文本值做一些事情
var textValue = ("input[x]").val();
Run Code Online (Sandbox Code Playgroud)
现在的问题是它落后于一个键,所以如果我的文本框中写着'他'并且我输入'l',那么我希望我的textValue为'Hel',但它返回的是前一个值'He'因为可能这个角色还没有放在文本框中.
有没有办法让'Hel'脱离我的功能?
谢谢 :)
CMS*_*CMS 56
您可以尝试使用keyup事件:
$(selector).keyup(function() {
var textValue = $(this).val();
DoX();
});
Run Code Online (Sandbox Code Playgroud)
Vin*_*nie 27
如果由于某些其他原因而无法使用keypressed(因此您无法按照建议更改为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
});
Run Code Online (Sandbox Code Playgroud)