jQuery的按键()事件获取文本(jquery keypress() event get text

2019-08-05 06:18发布

我想,当一个按键上的文本框时要运行的功能,所以我有这样的代码:

$("input[x]").keypress(function() {
        DoX();
    })

这是工作正常,但在我的功能我想基于文本框中的文本值做一些事情

var textValue = ("input[x]").val();

现在,这里的问题是,它的一个关键,所以如果我的文本框说:“他和我键入一个“L”,那么我想我textValue是“赫尔”滞后,但它返回前一个值“他”因为那时的字符尚未把在文本框中呢。

有越来越“赫尔”在这里我的功能的一种方式?

谢谢 :)

Answer 1:

你可以尝试使用keyup事件:

$(selector).keyup(function() {
  var textValue = $(this).val();
  DoX();
});


Answer 2:

如果您使用的卡为的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

});


Answer 3:

使用onkeyup ,它会显示正确的价值。



Answer 4:

使用的setTimeout没有延迟。 后按键事件完成,所以你必须输入正确的值就会立即运行。

$("input[x]").keypress(function() {
  setTimeout(DoX);
});


文章来源: jquery keypress() event get text