Set focus to field in dynamically loaded DIV

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

    This runs on page load.

    <script type="text/javascript">
        $(function () {
            $("#header").focus();
        });
    </script>
    
    0 讨论(0)
  • 2020-12-08 04:50
    $(function (){
        $('body').on('keypress','.sobitie_snses input',function(e){
            if(e.keyCode==13){
                $(this).blur();
                var new_fild =  $(this).clone().val('');
                $(this).parent().append(new_fild);
                $(new_fild).focus();
            }
        });
    });
    

    most of error are because U use wrong object to set the prorepty or function. Use console.log(new_fild); to see to what object U try to set the prorepty or function.

    0 讨论(0)
  • 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

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

    If

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

    is not working then is there another element on your page with the id of header?

    Use firebug to run $("#header") and see what it returns.

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