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

前端之家收集整理的这篇文章主要介绍了jquery – 将焦点设置为动态加载的DIV中的字段前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
将焦点设置为动态加载的DIV中的特定字段的正确方法是什么?
  1. $("#display").load("?control=msgs"); // loads the HTML into the DIV
  2. $('#display').fadeIn("fast"); // display it
  3. $("tex#header").focus(); // ?? neither that
  4. $("input#header").focus(); // ?? nor that
  5. $('#display','#header').focus() // ?? nor that
  6. $("#header").focus(); // ?? nor that works

以下HTML被提取显示DIV:

  1. <div id="display">
  2. <form id="newHeaderForm" class="dataform" action="/" method="post">
  3. <input id="to" type="hidden" value="22" name="to"/>
  4. <dl>
  5. <dt>Header</dt>
  6. <dd>
  7. <input id="header" class="large" type="text" name="header" value="" maxlength="128"/>
  8. </dd>
  9. </form>
  10. </div>

非常感谢!

解决方法

load()函数是一个异步函数。你应该在load()调用完成后设置焦点,这是在load()的回调函数中,因为否则你通过#header引用的元素还不存在。例如:
  1. $("#display").load("?control=msgs",{},function() {
  2. $('#header').focus();
  3. });

我有问题,我甚至与这个解决方案,所以我做了一个setTimeout在回调和设置焦点在超时,使/真正/确保元素存在。

猜你在找的jQuery相关文章