Javascript jquery 专注于负载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7814361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:42:08  来源:igfitidea点击:

jquery focus on load

javascriptjqueryfocus

提问by immobiluser

How to set the focus on a html element ?

如何将焦点设置在 html 元素上?

I use document.getElementById('ID_HTML_wanted').focus();but my html element "ID_HTML_wanted" as not the focus. I user jquery api .focus

我使用document.getElementById('ID_HTML_wanted').focus();但我的 html 元素“ID_HTML_wanted”不是焦点。我用户 jquery api .focus

回答by genesis

Try to wrap your code to this code so it executes AFTER DOM is ready

尝试将您的代码包装到此代码中,以便在 DOM 准备好后执行

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

so it will become

所以它会变成

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

However, your element't don't have .focus() method, if you want to REALLY use jQuery's one, use

但是,您的元素没有 .focus() 方法,如果您想真正使用 jQuery 的方法,请使用

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

回答by immobiluser

Sorry, i have effectively omit to set focus when DOM is ready :

抱歉,当 DOM 准备好时,我实际上省略了设置焦点:

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

All three of the following syntaxes of .ready()are equivalent:

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

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