【问题标题】:jquery focus on loadjquery专注于负载
【发布时间】:2011-10-18 22:10:24
【问题描述】:

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

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

【问题讨论】:

  • 愚蠢,当 DOM 准备就绪时,我忽略了设置焦点:$( document ).ready(function() { document.getElementById('ID_HTML_wanted').focus(); });跨度>

标签: javascript jquery focus


【解决方案1】:

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

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

所以它会变成

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

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

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

【讨论】:

  • 是的,我很愚蠢,当 DOM 准备好时,我忽略了设置焦点:$( document ).ready(function() { $("#ID_HTML_wanted").focus(); });
【解决方案2】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多