Set focus to field in dynamically loaded DIV

前端 未结 10 1220
心在旅途
心在旅途 2020-12-08 04:26

What is the proper method to set the focus to a specific field within a dynamically loaded DIV?

$(\"#display\").load(\"?control=msgs\"); // loads the HTML in         


        
相关标签:
10条回答
  • 2020-12-08 04:36

    The load() function is an asynchronous function. You should set the focus after the load() call finishes, that is in the callback function of load(), because otherwise the element you are referring to by #header, does not yet exist. For example:

    $("#display").load("?control=msgs", {}, function() { 
      $('#header').focus();
    }); 
    

    I had issues myself even with this solution, so i did a setTimeout in the callback and set the focus in the timeout to make /really/ sure the element exists.

    0 讨论(0)
  • 2020-12-08 04:37

    As Omu pointed out, you must set the focus in a document ready function. jQuery provides it for you. And do select on an id. For example, if you have a login page:

    $(function() { $("#login-user-name").focus(); }); // jQuery rocks!
    
    0 讨论(0)
  • 2020-12-08 04:38
    $("#display").load("?control=msgs", {}, function() { 
      $('#header').focus();
    });
    

    i tried it but it doesn't work, please give me more advice to resolve this problem. thanks for your help

    0 讨论(0)
  • 2020-12-08 04:40
    $("#header").attr('tabindex', -1).focus();
    
    0 讨论(0)
  • 2020-12-08 04:45

    Dynamically added items have to be added to the DOM... clone().append() adds it to the DOM... which allows it to be selected via jquery.

    0 讨论(0)
  • 2020-12-08 04:48

    Have you tried simply selecting by Id?

    $("#header").focus();
    

    Seeing as Ids should be unique, there's no need to have a more specific selector.

    0 讨论(0)
提交回复
热议问题