将焦点设置到动态加载的 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 并将焦点设置在超时中以确保/真正/确定元素存在。
关于jquery - 将焦点设置到动态加载的 DIV 中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1433742/