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

Lia*_*nat 15 html javascript asp.net-mvc html-helper focus

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

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

我试图使用javascript,这没有多大帮助:

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

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

Dar*_*rov 29

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

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

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

说完这个不是我推荐你的解决方案.为了解决所有这些问题,我通常将css类应用于文本框:

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

其中email类的定义如下:

.email {
    width: 190px;
    border: 0;
}
Run Code Online (Sandbox Code Playgroud)

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

$(function() {
    $('input.email').focus();
});
Run Code Online (Sandbox Code Playgroud)


小智 7

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