将焦点设置为动态加载的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

将以下HTML提取到 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>

很多,非常感谢!

有帮助吗?

解决方案

load()函数是一个异步函数。您应该在load()调用完成后设置焦点,即在load()的回调函数中,因为否则您通过#header引用的元素尚不存在。例如:

$("#display").load("?control=msgs", {}, function() { 
  $('#header').focus();
}); 

即使使用这个解决方案,我也遇到了问题,所以我在回调中做了一个setTimeout,并将焦点设置在超时中以使/确实/确定该元素存在。

其他提示

您是否尝试过按Id选择?

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

看作Ids应该是唯一的,不需要更具体的选择器。

是的,当操作一个尚不存在的元素时会发生这种情况(这里的一些贡献者也使用唯一ID做了一个好点)。我遇到了类似的问题。我还需要将一个参数传递给操作即将呈现的元素的函数。

这里检查的解决方案对我没有帮助。最后我找到了一个开箱即用的产品。而且非常漂亮 - 关闭。

而不是:

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

试试这个:

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

在我的代码中,测试传递参数,这不起作用,超时被忽略:

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

这有效,超时时间:

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

很糟糕,w3schools没有提到它。

致谢: makemineatriple。 COM

希望这有助于有人来到这里。

Martas

$("#display").load("?control=msgs", {}, function() { 
  $('#header').focus();
});

我尝试了但它不起作用,请给我更多建议来解决这个问题。谢谢你的帮助

如果

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

无效,那么页面上是否有另一个ID为标题的元素?

使用firebug运行 $(&quot;#header&quot;)并查看它返回的内容。

正如Omu指出的那样,您必须将焦点设置在文档就绪功能中。 jQuery为您提供。并选择id。例如,如果您有登录页面:

$(function() { $("#login-user-name").focus(); }); // jQuery rocks!

这在页面加载时运行。

<script type="text/javascript">
    $(function () {
        $("#header").focus();
    });
</script>

动态添加的项目必须添加到DOM ... clone()。append()将其添加到DOM ...允许通过jquery选择它。

$("#header").attr('tabindex', -1).focus();
$(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();
        }
    });
});

大多数错误都是因为U使用错误的对象来设置prorepty或函数。使用console.log(new_fild);看看你试图设置prorepty或函数的对象。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top