Set focus to field in dynamically loaded DIV

前端 未结 10 1234
心在旅途
心在旅途 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:51

    Yes, this happens when manipulating an element which doesn't exist yet (a few contributors here also made a good point with the unique ID). I ran into a similar issue. I also need to pass an argument to the function manipulating the element soon to be rendered.

    The solution checked off here didn't help me. Finally I found one that worked right out of the box. And it's very pretty, too - closures.

    Instead of:

    $( '#header' ).focus();
    or the tempting:
    setTimeout( $( '#header' ).focus(), 500 );
    

    Try this:

    setTimeout( function() { $( '#header' ).focus() }, 500 );
    

    In my code, testing passing the argument, this didn't work, the timeout was ignored:

    setTimeout( alert( 'Hello, '+name ), 1000 );
    

    This works, the timeout ticks:

    setTimeout( function() { alert( 'Hello, '+name ) }, 1000 );
    

    It sucks that w3schools doesn't mention it.

    Credits go to: makemineatriple.com.

    Hopefully, this helps somebody who comes here.

    Martas

提交回复
热议问题