Jquery ajax:一个新的输入字段在获得焦点后失去焦点

时间:2021-02-26 20:18:11

I tried to focus on a new created input element during ajax update, but the focus is lost somehow.

我试图在ajax更新期间专注于新创建的输入元素,但焦点会以某种方式丢失。

       var options = {
            url: aURL,
            type: "POST",                
            dataType: "xml",
            data: params,         
            success: function(responseData, status, xhr) {
                // replace DOM element
                $(".placeholder").html(responseData);
            }
        };

        $.ajax(options);

Inside the responseData, there is a script

在responseData中,有一个脚本

<script>$(function(){createInputAndFocus();});</script>

The script will be executed during the ajax DOM update.

该脚本将在ajax DOM更新期间执行。

function createInputAndFocus() {
     $(".placeholder").append('<input type="text" id="foo"/>');
     $(".placeholder").find("#foo").focus();

     // debug: check if it is focused
     console.log("active element: " + document.activeElement.id);
}

From the browser console, the created input (foo) is focused. But after the ajax is completed, it is not focused(highlighted) on the screen. From the console, verified it is not focused. document.activeElement is the same as the one before ajax update.

从浏览器控制台,聚焦创建的输入(foo)。但是在ajax完成之后,它没有在屏幕上聚焦(突出显示)。从控制台,验证它没有集中。 document.activeElement与ajax更新之前的相同。

Does Jquery restore the original focus after ajax? How to focus on new input element after ajax update? I tried to set up a timer

Jquery在ajax之后恢复原始焦点吗? ajax更新后如何关注新的输入元素?我试着设置一个计时器

function createInputAndFocus() {
         $(".placeholder").append('<input type="text" id="foo"/>');
         $(".placeholder").find("#foo").focus();

         setTimeout(function() {$(".placeholder").find("#foo").focus();}, 3000);
    }

Timer works. Timer is not a safe solution. the timeout might be fired too early if setting the timeout too short, and users have to wait if setting it too long. Thanks for help.

定时器工作。定时器不是一个安全的解决方案如果将超时设置得太短,则可能会过早触发超时,并且用户必须等待设置太长时间。感谢帮助。

1 个解决方案

#1


0  

Can you just call the

你能打电话吗?

createInputAndFocus();

straight from the success() method? Otherwise, you could try adding async=false to the options, but that may lower performance.

直接来自success()方法?否则,您可以尝试在选项中添加async = false,但这可能会降低性能。

#1


0  

Can you just call the

你能打电话吗?

createInputAndFocus();

straight from the success() method? Otherwise, you could try adding async=false to the options, but that may lower performance.

直接来自success()方法?否则,您可以尝试在选项中添加async = false,但这可能会降低性能。