jQuery .focus doesn’t actually focus a newly created element

后端 未结 8 1888
清歌不尽
清歌不尽 2020-12-08 03:38

Let’s say I have this markup:

First paragraph

相关标签:
8条回答
  • 2020-12-08 04:13

    You can assign tabidex and then you can set focus to that element

    $('#table').attr("tabindex",1).focus();
    

    This will work for Div Table etc which can't get focus by itself.

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

    There's no problem with your code, it's just that a paragraph or div tag can't receive focus. Focus can only be given to things you can interact with, such as links, input elements, textareas, etc.

    To scroll the window to this newly added element, you can use a plugin such as ScrollTo.

    On a side note, your code could be simplified a bit:

    var html = "<div id=\"newP\"><p>New paragraph</p></div>";
    $("#content").append(html);
    $("#newP p").focus();
    
    var html = "<div id=\"newP\"><p>New paragraph</p></div>";
    $(html)
        .appendTo('#content')
        .focus()   // or scrollTo(), now...
    ;
    
    0 讨论(0)
提交回复
热议问题