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

标签 javascript html asp.net-mvc focus html-helper

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

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

我尝试使用 javascript 但没有太大帮助:

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

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

最佳答案

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

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

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

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

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

email 类定义如下:

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

然后使用popular javascript framework在 DOM 准备就绪时设置焦点:

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

关于javascript - 如何将焦点设置到文本框 Html.TextBoxFor - mvc 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2951405/

相关文章:

asp.net-mvc - ASP.Net 5 project.json脚本命令的完整列表? (Visual Studio 2015)

javascript - 将两种不同类型的 div 附加到单个容器

javascript - jquery - colorbox - 将函数添加到弹出窗口

html - Bootstrap 4 order Masonry-like column cards 水平而不是垂直

jQuery on event 在其他页面上查找元素

asp.net-mvc - SignalR 持久连接的超时时间是多少?

asp.net-mvc - Html.RenderPartial 给我奇怪的过载错误?

javascript - React - 获取输入

javascript - Angular 2 模板语法

html - 兼容性 View 使我的页面出错?