将焦点设置在 jQuery 中的文本框上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5772426/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:48:33  来源:igfitidea点击:

Set focus on textbox in jQuery

jqueryajaxtextbox

提问by user478636

I've made a textbox, and when the user types in a command. That command is passed to a php file using jquery-ajax and executed on the server, and the results are returned. These results are output on the browser by creating div tag.

我制作了一个文本框,当用户输入命令时。该命令使用 jquery-ajax 传递到一个 php 文件并在服务器上执行,并返回结果。这些结果通过创建 div 标签输出到浏览器上。

The problem is that I'm appending the div tag. As I'm appending, my textbox seems be going out of focus, I have to scroll down the page to be able to see what I'm typing.

问题是我附加了 div 标签。当我追加时,我的文本框似乎失去了焦点,我必须向下滚动页面才能看到我正在输入的内容。

This is the function that receives the command I type in the textbox.

这是接收我在文本框中键入的命令的函数。

$(function() {
    $('#cmd').keydown(

    function(event) {
        if (event.keyCode == 13) {
            event.preventDefault(); /*you can call your function here*/
            var tmp = $(this).val();
            $('#cmd').val('');
            commands.push(tmp);

            MyFunction(tmp);
            /*still you can it here*/
        }
    });
});

This function receives the returned value, and creates the div tag.

此函数接收返回值,并创建 div 标签。

function MyFunction(msg) {
    var cmdStr = msg;
    $.ajax({
        url: 'exec.php',
        dataType: 'text',
        data: {
            q: cmdStr
        },
        success: function(response) { 

    $('#output').append("<div class=type> www-data@ubuntu:~# " + cmdStr +"</div>" + "<div class=output>" + response + "</div>");
        }

    });

}

回答by mattsven

Try this:

尝试这个:

success: function(response){
    $("#output").append("<div class=type> www-data@ubuntu:~# " + cmdStr +"</div>" + "<div class=output>" + response + "</div>");
    $("#cmd").focus(); //Wil focus your textbox
}

回答by Rory McCrossan

Try this:

尝试这个:

$(function() {
    $('#cmd').keydown(

    function(event) {
        if (event.keyCode == 13) {
            event.preventDefault(); /*you can call your function here*/
            var tmp = $(this).val();
            $('#cmd').val('');
            commands.push(tmp);

            MyFunction(tmp);
            $(this).focus(); // Set the focus back on to the #cmd element
        }
    });
});