嗨,我的表格上有表格。当页面加载被触发时,我将焦点设置为第一个输入[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);
}
}
});
}
});
最佳答案
问题是您的元素添加在 $.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');
关于javascript - jquery setfocus() 新插入的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4477131/