jQuery在页面加载时设置焦点

6

如何设置HTML元素的焦点?

我使用document.getElementById('ID_HTML_wanted').focus();,但我的HTML元素“ID_HTML_wanted”没有焦点。我使用jQuery API .focus


1
笨蛋,我在DOM准备就绪时忘记设置焦点:$( document ).ready(function() { document.getElementById('ID_HTML_wanted').focus(); }); - immobiluser
2个回答

11

尝试将你的代码包装在这段代码中,以便它在 DOM 就绪后执行

$(function(){
    //your code
});

所以它将变成

$(function(){
    document.getElementById('ID_HTML_wanted').focus();
});

然而,您的元素没有 .focus() 方法。如果您确实想使用 jQuery 的 focus() 方法,则需要使用

$(function(){
    $("#ID_HTML_wanted").focus();
});

是的,我很愚蠢,当DOM准备好时,我忘记设置焦点: $(document).ready(function(){ $(“#ID_HTML_wanted”)。focus(); }); - immobiluser

2
抱歉,我在DOM准备就绪时忘记设置焦点了。
$( document ).ready(function() {
  $("#ID_HTML_wanted").focus();
});

.ready() 的以下三种语法是等效的:

$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接