Set focus to field in dynamically loaded DIV

前端 未结 10 1219
心在旅途
心在旅途 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.

提交回复
热议问题