Set focus to field in dynamically loaded DIV

2019-01-16 18:02发布

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 into the DIV
$('#display').fadeIn("fast"); // display it
$("tex#header").focus();          // ?? neither that
$("input#header").focus();        // ?? nor that
$('#display', '#header').focus()  // ?? nor that
$("#header").focus();             // ?? nor that works

The following HTML is fetched into the display DIV:

<div id="display">
<form id="newHeaderForm" class="dataform" action="/" method="post">
    <input id="to" type="hidden" value="22" name="to"/>
    <dl>
        <dt>Header</dt>
        <dd>
            <input id="header" class="large" type="text" name="header" value="" maxlength="128"/>
        </dd>
 </form>
 </div>

Many, many thanks!

10条回答
时光不老,我们不散
2楼-- · 2019-01-16 18:32
$(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.

查看更多
做个烂人
3楼-- · 2019-01-16 18:34
$("#header").attr('tabindex', -1).focus();
查看更多
再贱就再见
4楼-- · 2019-01-16 18: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!
查看更多
够拽才男人
5楼-- · 2019-01-16 18:39

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.

查看更多
霸刀☆藐视天下
6楼-- · 2019-01-16 18:39

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.

查看更多
疯言疯语
7楼-- · 2019-01-16 18:43

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.

查看更多
登录 后发表回答