使用Jquery的文本框文本捕获总是'后面的一个字符'

Ser*_*gio 1 jquery

我试图使用jquery和keydown事件捕获用户输入.

这是我的代码:

 $(document).ready(function() {
        $("#searchText").keydown(function() {
            var filter = jQuery.trim($(this).val());
            if (filter.length > 3 || filter.length == 0) {
                //hit the index action again and pass the keyword
                $("#results").fadeOut("fast");
                $("#results").load("/Organisation/Index?keyword=" + filter, null, function() {
                    $(this).fadeIn("fast");
                });
            }
        });
    });
Run Code Online (Sandbox Code Playgroud)

在mo,这是有效的,除了被捕获的字符串似乎总是被一个字符"过时"的事实,我必须按另一个键来实际获取我希望传递给我的动作的文本.

提前致谢!

Naw*_*Man 8

你的问题是'keydown'事件.由于在按下按键时进行了值的处理,其中新按下的字符尚未被记入输入.通过使用'keyup',在新按下的字符已添加到值之后完成处理.

 $(document).ready(function() {
        $("#searchText").keyup(function() {
            var filter = jQuery.trim($(this).val());
            if (filter.length < 3 || filter.length == 0) {
                //hit the index action again and pass the keyword
                $("#results").fadeOut("fast");
                $("#results").load("/Organisation/Index?keyword=" + filter, null, function() {
                    $(this).fadeIn("fast");
                });
            }
        });
    });
Run Code Online (Sandbox Code Playgroud)