将焦点设置为动态加载的DIV中的字段

将焦点设置为动态加载的DIV中的字段

本文介绍了将焦点设置为动态加载的DIV中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $(#)

?显示 )的负载( 对照=封邮件); //将HTML加载到DIV
$('#display')。fadeIn(fast); //显示
$(tex#header)。focus(); //?既不是
$(input#header)。 //?也不是
$('#display','#header')。focus()//?也不是
$(#header)。 //?也没有这样做

下面的HTML被提取到显示

 < div id =display> 
< form id =newHeaderFormclass =dataformaction =/method =post>
< input id =totype =hiddenvalue =22name =to/>
< dl>
< dt>标头< / dt>
< dd>
< input id =headerclass =largetype =textname =headervalue =maxlength =128/>
< / dd>
< / form>
< / div>

很多,非常感谢!

解决方案

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

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

即使使用此解决方案,我也遇到了问题,所以我在回调函数中设置了setTimeout,在超时使/确实/确定元素存在。


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!

解决方案

The load() function is an asynchronous function. You should set the focus after the load() call finishes, that is in the callback function of load(), because otherwise the element you are referring to by #header, does not yet exist. For example:

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

I had issues myself even with this solution, so i did a setTimeout in the callback and set the focus in the timeout to make /really/ sure the element exists.

这篇关于将焦点设置为动态加载的DIV中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 18:01