将 ASP.Net 控件 ID 发送到 JavaScript 函数

send ASP.Net Control Id To a JavaScript Function

本文关键字:JavaScript 函数 ID ASP Net 控件      更新时间:2023-09-26

我有 2 个视图。view1 上的最后一个控件是 txtName,view2 上的第一个控件是 txtAge。需要在 TAB 上将焦点从 txtName 更改为 txtAge,但我未能实现这一目标。

.ASPX:

<asp:Multiview ID ="multiview1" runat="server" ActiveViewIndex="0">
  <asp:view ID="view1" runat="server">
  <asp:Textbox id="txtName" runat="server" 
onfocusout="SetFocus('<%=txtAge.ClientId%>');"></asp:TextBox>
  </asp:view>
<asp:view ID ="view2" runat="server">
   <asp:Textbox id="txtAge" runat="server" ></asp:TextBox>
</asp:view>
</asp:Multiview>

.JS:

function SetFocus(controlId){
    /*alert(controlId);*/
 document.getElementById(controlId).focus();
}

当我检查警报时,它会在弹出窗口中显示<%=txtAge.ClientId%>。这是哪里出了问题。

这是我的新发现:

目标控件位于同一视图中时,此代码运行良好,但当它位于另一个视图中时,则不然。所以我认为,还应该做一些其他事情来先改变视图,然后再担心焦点:

<asp:Textbox id="txtName" runat="server" 
onfocusout="SetFocus();"></asp:TextBox>
function SetFocus(){
 document.getElementById('<%=txtEmail.ClientID%>').focus();
 /* txtEmail is in the same view 'view1' as in txtName */
}

您可以尝试在服务器端代码中设置它:

txtName.Attributes["onfocusout"] = String.Format("SetFocus('{0}');", txtAge.ClientId); 

也许使用tabindex就足够了http://msdn.microsoft.com/en-us/library/ms178231%28v=vs.100%29.aspx

它使用内置功能而不是JavaScript。

如果您使用 4.x asp.net 则可以使用 clientidmode=statichttp://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx

<asp:Multiview ID ="multiview1" runat="server" ActiveViewIndex="0">
    <asp:view ID="view1" runat="server">
        <!-- other controls -->
        <asp:Textbox id="txtName" runat="server" TabIndex="1"/>
    </asp:view>
    <asp:view ID ="view2" runat="server">
        <asp:Textbox id="txtAge" runat="server" TabIndex="2"/>
        <!-- other controls -->
    </asp:view>
</asp:Multiview>

编辑如果你不介意使用jQuery。您可以在<asp:View..周围环绕一个div,然后执行以下操作:

$("div.view input:last-child").on("change", function(){
    $(this).parent().next().find("input:first-child").focus();
});

请记住,这是伪代码。这只是一个想法。

试试这个,看看它是否更好。

 <asp:Textbox id="txtName" runat="server" 
onfocusout='<%= String.Format("SetFocus('"{0}'");", txtAge.ClientId) %>'></asp:TextBox>
在这种情况下,无法使用

内联块设置属性...如您所见,您正在获取文字<%=txtAge.ClientId%>文本,并且您没有获得预期的已处理值。

您有两个明显的解决方案...

第一个(Yuriy 在他的答案中已经给了你)是从后面的代码中设置它......

txtName.Attributes["onfocusout"] = String.Format("SetFocus('{0}');", 
                                                 txtAge.ClientId);

(免责声明,我不知道MultiView是什么,因为我从未使用过它,所以我不能 100% 确定下面的第二个选项是否真的适用于您的场景。此外,它是未经测试的代码。

另一种是使用穆拉利在他的回答中提供的内容,但要进行额外的操作......

<asp:Textbox id="txtName" runat="server" onfocusout="SetFocus(this);" />
function SetFocus(nameCtrl) {
  var ageId = nameCtrl.id.replace(/txtName/,"txtAge");
  var ageCtrl = document.getElementById(ageId);
  ageCtrl.focus();
}

更改行onfocusout="SetFocus('<%=txtAge.ClientId%>');"></asp:TextBox>onfocusout="SetFocus('txtAge');"></asp:TextBox>

您无需发送客户端 ID