javascript jquery setfocus() 新插入的元素

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

jquery setfocus() newly inserted elements

javascriptajaxjquery

提问by AEMLoviji

hi i have table on the form. when page load is fired i set focus to the first input[type='text']. and i post the form with ajax and if all goes right i add new row to the top of the table. and now i cant set focus to new inserted row.here is my javascript code:

嗨,我在表格上有表格。当页面加载被触发时,我将焦点设置为第一个输入 [type='text']。我用ajax发布表单,如果一切顺利,我将新行添加到表格顶部。现在我无法将焦点设置到新插入的行上。这是我的 javascript 代码:

  $(document).keypress(function (e) {
            var key_code = e.which;
            if (key_code == 13) {
                $.ajax({
                    type: "POST",
                    url: "AddNewPayPackage",
                    data: $("#AddPackPayment").serialize(),
                    dataType: "text/plain",
                    success: function (response) {
                        if (response == "Saved") {
                            $('#myTable tbody tr:first input:text').removeAttr("tabindex");

                            $.get('AddNewPayPackage', function (data) {
                                $('#myTable tbody tr:first').before("<tr>" + data + "</tr>");
                            });

                            $('.input-validation-error').removeClass('input-validation-error');
                            $("form :input[type='text']:first").focus();
                        }
                        else {
                            $("#myTable tbody tr:first").html(response);
                        }
                    }
                });
            }
        });    

回答by Nick Craver

The problem is that your element added in the $.get()callback is added later, when the server response comes back with the content...so you need to focus afterthat happens...in the callback, like this:

问题是,你在添加元素$.get()的回调被添加,当服务器响应返回与内容...所以你需要关注之后这种情况发生......在回调,就像这样:

$.get('AddNewPayPackage', function (data) {
    $('#myTable tbody tr:first').before("<tr>" + data + "</tr>");
    $("form :input[type='text']:first").focus(); //needs to run here
});
$('.input-validation-error').removeClass('input-validation-error');

回答by Stuart Burrows

Looks like a typo:

看起来像一个错字:

$("form :input[type='text']:first").focus();

should be

应该

$("form input[type='text']:first").focus();