Javascript 如何将焦点设置到文本框 Html.TextBoxFor - mvc 2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2951405/
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-23 02:38:21  来源:igfitidea点击:

How do I set focus to a text box Html.TextBoxFor - mvc 2

javascripthtmlasp.net-mvcfocushtml-helper

提问by Liad Livnat

I'm trying to set focus on a text box which is generated in the following way:

我正在尝试将焦点设置在以以下方式生成的文本框上:

<%=Html.TextBoxFor(model => model.Email, new { style = "width:190px;Border:0px", maxsize = 190 })%>

I tried to use javascript which didn't help much :

我尝试使用 javascript 并没有多大帮助:

   <script type="text/javascript">
       var txtBox = document.getElementById("Email");
       if (txtBox != null) txtBox.focus();
    </script>

How do I set focus to a text box Html.TextBoxFor in mvc 2 ?

如何将焦点设置到 mvc 2 中的文本框 Html.TextBoxFor ?

回答by Darin Dimitrov

Where are you writing this javascript? You need to make sure that the DOM is loaded:

你在哪里写这个javascript?您需要确保 DOM 已加载:

window.onload = function() {
    var txtBox = document.getElementById("Email"); 
    if (txtBox != null) { 
        txtBox.focus();
    }
};

Also HTML helpers might generate a different ID depending on the context: for example if you are calling the TextBoxForinside an editor template.

此外,HTML 助手可能会根据上下文生成不同的 ID:例如,如果您正在调用TextBoxFor编辑器模板的内部。

Having said this it is not the solution I would recommend you. To solve all those problems I usually apply a css class to the textbox:

话虽如此,这不是我推荐您的解决方案。为了解决所有这些问题,我通常将 css 类应用于文本框:

<%=Html.TextBoxFor(
    model => model.Email, 
    new { @class = "email", maxsize = "190" }) %>

where emailclass is defined like this:

其中emailclass 定义如下:

.email {
    width: 190px;
    border: 0;
}

and then use a popular javascript frameworkto set the focus when the DOM is ready:

然后使用流行的 javascript 框架在 DOM 准备好时设置焦点:

$(function() {
    $('input.email').focus();
});

回答by AR M

you can use autofocus in HTML5. <%=Html.TextBoxFor(model => model.Email, new { style = "width:190px;Border:0px", maxsize = 190 ,autofocus = "autofocus" })%>

您可以在HTML5 中使用自动对焦。 <%=Html.TextBoxFor(model => model.Email, new { style = "width:190px;Border:0px", maxsize = 190 ,autofocus = "autofocus" })%>