【问题标题】:How to focus on input box when page loads?页面加载时如何关注输入框?
【发布时间】:2015-01-12 04:58:20
【问题描述】:

当我的页面首次加载时,我正在尝试关注页面上的第一个文本框或输入框。所以我希望页面加载时在第一个文本框中显示一个闪烁的光标。我搜索了许多解决方案,所有结果都相同:使用 .focus() 协议。我已经尝试过,但仍然无法正常工作。

这是在我的初始化函数中:

$(document).ready(function () {
                $('#TranslationTextBox:first').focus();
                $(".parametersNumericbox:first").focus();
            });

            $(".parametersNumericbox").focus(function () {
                var input = $(this);
                setTimeout(function () {
                    input.select();
                });
            });

只有当我点击几次时,它才会将我带到第一个文本框。

编辑:html 代码(使用 Kendo UI):

 <td id="TranslationTextBox">
                            @(Html.Kendo().NumericTextBoxFor<double>(model => model.Translation).Format("#").Decimals(0).Min(0)
                                  .HtmlAttributes(new { @class = "parametersNumericbox" })
                                  .Events(e => e
                                      .Change("TranslationTextBoxChanged")
                                      ))
                        </td>

我目前遇到的问题是由于某种原因,焦点似乎转到了页面上文本字段之前的按钮。

【问题讨论】:

  • 您正试图关注ready() 上的多个对象。此外,如果不查看您对 HTML 代码的了解,也很难判断。
  • 其实应该是一样的。相同的文本字段。
  • 也不是第二段代码,选择自己的onfocus回调是不必要的吗?
  • 您可能想要 $(".parametersNumericbox:first input").focus(); 之类的东西在 first td 中指定文本框。
  • 您的第一个 .focus() 正在尝试将焦点设置到 td 元素,而不是 td 内的元素。

标签: javascript jquery kendo-ui


【解决方案1】:

当然可以使用 Javascript,但也可以使用 HTML:

<input type="text" autofocus>

在 jQuery 中你可以这样做:

$("input, textarea, select").filter(":first").focus();

您的代码的一个问题似乎是您正在关注多个项目。当您这样做时,上次聚焦的项目将获得焦点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 2015-03-08
    • 2011-04-15
    相关资源
    最近更新 更多