You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AJAX局部刷新后无法恢复元素焦点的问题求助

问题描述

我有一个包含输入框的局部视图,会将当前获得焦点的元素ID存储在父表单的隐藏输入框focusHolder中。通过AJAX调用刷新该局部元素后,希望将焦点恢复到之前选中的元素。目前存储/获取元素ID、局部刷新及数据更新功能均正常,但最终设置焦点的操作没有效果。

环境:Chrome浏览器,基于VS2022 + ASP.NET Core 6开发。

问题代码
$(document).on('change', ".updateable", function (event) {
    //if (event.type === 'change') {
    //$(".updateable").change(function() {
    console.log("focusHolder.val - pre refresh " + $('#focusHolder').val());
    var subAgent = $('#subagentId').attr('value');
    var rowId = $(this).attr('rowID');

    var updatedField = $(this).attr("id").substring(0, $(this).attr("id").length - (rowId.length + 1));
    var updatedValue = $(this).val(); 
    $.ajax({
        url: '/Rating/UpdateCurrentRates',
        type: 'POST',
        data: { subAgent_ID: subAgent, row_ID: rowId, fieldName: updatedField, newValue: updatedValue },
        success: function (result) {
            $("#newRates").html(result);
        },
        error: function (xhr, exception) {
            //alert;
            return false;
        }
    })
        //    .done(function () {

        //    console.log("focused - done " + focused);
        //    var focused = $('#focusHolder').val();
        //    $(focused).focus();

        //})
        .always(function () {

            var focused = $('#focusHolder').val();
            console.log("focused - always " + focused);
$(focused).focus();

        });
    console.log("ajax call finished");

});
解决方案

问题核心在于always回调的执行时机:AJAX请求完成后立即触发always,但此时success里的$("#newRates").html(result)可能还未完成DOM渲染,新元素尚未被插入页面,导致无法找到目标元素执行焦点设置。

具体修复步骤

  1. 将焦点恢复逻辑移至success回调末尾
    确保局部视图的DOM更新完成后,再执行焦点设置操作,此时新元素已存在于页面中。

  2. 校验选择器格式
    若隐藏框focusHolder存储的是纯元素ID(如input_123),必须在选择器前添加#,否则jQuery无法定位到元素。

修改后的代码

$(document).on('change', ".updateable", function (event) {
    console.log("focusHolder.val - pre refresh " + $('#focusHolder').val());
    var subAgent = $('#subagentId').attr('value');
    var rowId = $(this).attr('rowID');

    var updatedField = $(this).attr("id").substring(0, $(this).attr("id").length - (rowId.length + 1));
    var updatedValue = $(this).val(); 
    $.ajax({
        url: '/Rating/UpdateCurrentRates',
        type: 'POST',
        data: { subAgent_ID: subAgent, row_ID: rowId, fieldName: updatedField, newValue: updatedValue },
        success: function (result) {
            $("#newRates").html(result);
            // DOM更新完成后恢复焦点
            var focusedId = $('#focusHolder').val();
            // 补全选择器前缀,确保能定位到元素
            var targetSelector = focusedId.startsWith('#') ? focusedId : '#' + focusedId;
            $(targetSelector).focus();
            console.log("尝试恢复焦点到:" + targetSelector);
        },
        error: function (xhr, exception) {
            console.error("AJAX请求失败:", xhr, exception);
            return false;
        }
    })
    .always(function () {
        console.log("AJAX请求完成");
    });
    console.log("ajax call finished");
});

额外调试建议

  • 在控制台打印targetSelector及$(targetSelector).length,确认是否成功选中目标元素。
  • 若仍存在延迟问题,可尝试用setTimeout包裹焦点设置操作(如延迟100ms),确保DOM渲染完全结束。

内容的提问来源于stack exchange,提问作者DazzaJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 11:31:03