简体   繁体   English

单击asp标签后如何在文本框和/或控件上设置焦点?

[英]How to set focus on textbox and/or control after clicking an asp label?

I would like to set the focus on a textbox and/or control after clicking an asp label? 我想在单击asp标签后将焦点设置在文本框和/或控件上吗? Can some explain to me how to do this? 可以给我解释一下怎么做吗? Similar to doing a 类似于做一个

<label for="txtBoxID">Blah</label>

You can also do this 您也可以这样做

<label for="<%=txtName.ClientID%>">Name:</label>
<asp:TextBox runat="server" ID="txtName"></asp:TextBox>

or on dot 4. 或在点4。

<label for="txtName">Name: </label>
<asp:TextBox runat="server" ID="txtName" ClientIDMode="Static"></asp:TextBox>

and avoid JavaScript. 并避免使用JavaScript。

This is the Best way to write and avoid javascript 这是编写和避免javascript的最佳方法

<p>

<asp:Label ID="lblName" runat="server" AssociatedControlID="txtFirstName" Text="First Name: " />

<asp:TextBox ID="txtFirstName" runat="server" />

</p>

You can do it using Javascript or jQuery. 您可以使用Javascript或jQuery完成。

<label for="txtBoxID" onClientClick="SetMyFocus()">Blah</label>

<javascript>
function SetMyFocus()
{
    document.getElementById("MyTextBox").focus();
}
</javascript>

If you have a specific need of doing something in the server side on the click of the label, you shall have to handle the same in code behind and then set the client side script to fire up after reloading the page. 如果您特别需要单击标签在服务器端执行某些操作,则必须处理后面的代码,然后将客户端脚本设置为在重新加载页面后启动。 Use RegisterStartupScript for the same. 同样使用RegisterStartupScript

I'm assuming you want to do it completely on the client side to avoid a postback? 我假设您想完全在客户端完成此操作以避免回发?

You can use jQuery to set focus. 您可以使用jQuery设置焦点。 After adding a script reference to the jQuery library, you can use the following JavaScript in your page: 在添加对jQuery库的脚本引用之后,您可以在页面中使用以下JavaScript:

$(document).ready(function() {
     $("#labelId").click(function() {
          $("*[id$='txtBoxID']").focus()
     });
});

The "*[id$='txtBoxID']" selector allows you to select the ASP.NET server side ID of your textbox without any additional code. 使用“ * [id $ ='txtBoxID']”选择器,您可以选择文本框的ASP.NET服务器端ID,而无需任何其他代码。 Basically, it's saying "select any DOM element whose ID ends with txtBoxId." 基本上,这就是说“选择ID以txtBoxId结尾的任何DOM元素”。

You can add jQuery to your page with the following CDN script reference: 您可以使用以下CDN脚本参考将jQuery添加到页面中:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

A more generalized solution using jQuery: 使用jQuery的更通用的解决方案:

$(document).ready(function() {
     $("label[for]").click(function() {
          var inputid = '#' + $(this).attr('for');
          $(inputid).focus();
     });
});

Should handle all labels, as long as you correctly define the for attribute. 只要正确定义了for属性,就应该处理所有标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM