如何阻止 ASP.NET 更改 ID 以使用 jQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/497802/
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
How to stop ASP.NET from changing IDs in order to use jQuery
提问by ahmed
I have this label control in my web page
我的网页中有这个标签控件
<asp:Label ID="Label1" runat="server" Text="test"></asp:Label>
And when the page rendered the id of the control changes to something like this
当页面呈现控件的 id 更改为这样的
<span id="ctl00_ContentPlaceHolder1_Label3">test</span>
How can I stop asp.net from changing IDs in order to perform a jQuery operation like this
如何阻止 asp.net 更改 ID 以执行这样的 jQuery 操作
$('#label1').html(xml);
采纳答案by Jon Erickson
instead of using this selector
而不是使用这个选择器
$('#Label1')
use this one, basically you are using the classic asp inline server side code.
使用这个,基本上你使用的是经典的 asp 内联服务器端代码。
$('#<%= Label1.ClientID %>')
this will insert whatever ID that is generated to be placed as a literal.
这将插入生成的任何 ID 作为文字放置。
If you wish to use external files then I would suggest you create an obj that is global on the page to hold all of your client ids and then reference that obj within your external files (not ideal but it is a solution)
如果您希望使用外部文件,那么我建议您在页面上创建一个全局 obj 以保存所有客户端 ID,然后在您的外部文件中引用该 obj(不理想,但它是一个解决方案)
var MyClientIDs = {
Label1 = '<%= Label1.ClientID %>',
Label2 = '<%= Label2.ClientID %>',
Textbox1 = '<%= Textbox1.ClientID %>',
Textbox2 = '<%= Textbox2.ClientID %>'
};
and then in your external file you can access Label1 for example: $('#' + MyClientIDs.Label1)
然后在您的外部文件中,您可以访问 Label1 例如: $('#' + MyClientIDs.Label1)
回答by David d C e Freitas
.NET 4 now has the ability to let you choose your ClientIDMode:
.NET 4 现在可以让您选择您的ClientIDMode:
Type: System.Web.UI.ClientIDMode
A value that indicates how the ClientID property is generated. The default is Inherit.
指示如何生成 ClientID 属性的值。默认为继承。
AutoIDThe ClientID value is generated by concatenating the ID values of each parent naming container with the ID value of the control. In data-binding scenarios where multiple instances of a control are rendered, an incrementing value is inserted in front of the control's ID value. Each segment is separated by an underscore character (_). This algorithm was used in versions of ASP.NET earlier than ASP.NET 4.
StaticThe ClientID value is set to the value of the ID property. If the control is a naming container, the control is used as the top of the hierarchy of naming containers for any controls that it contains.
PredictableThis algorithm is used for controls that are in data-bound controls. The ClientID value is generated by concatenating the ClientID value of the parent naming container with the ID value of the control. If the control is a data-bound control that generates multiple rows, the value of the data field specified in the ClientIDRowSuffix property is added at the end. For the GridView control, multiple data fields can be specified. If the ClientIDRowSuffix property is blank, a sequential number is added at the end instead of a data-field value. This number begins at zero and is incremented by 1 for each row. Each segment is separated by an underscore character (_).
InheritThe control inherits the ClientIDMode setting of its NamingContainer control.
AutoIDClientID 值是通过将每个父命名容器的 ID 值与控件的 ID 值连接起来生成的。在呈现控件的多个实例的数据绑定方案中,在控件的 ID 值前面插入一个递增值。每个段由下划线字符 (_) 分隔。该算法用于早于 ASP.NET 4 的 ASP.NET 版本。
静态ClientID 值设置为 ID 属性的值。如果控件是命名容器,则该控件将用作它包含的任何控件的命名容器层次结构的顶部。
可预测该算法用于数据绑定控件中的控件。ClientID 值是通过将父命名容器的 ClientID 值与控件的 ID 值串联而生成的。如果控件是生成多行的数据绑定控件,则在末尾添加 ClientIDRowSuffix 属性中指定的数据字段的值。对于 GridView 控件,可以指定多个数据字段。如果 ClientIDRowSuffix 属性为空,则会在末尾添加一个序列号而不是数据字段值。该数字从零开始,每行加 1。每个段由下划线字符 (_) 分隔。
继承该控件继承其 NamingContainer 控件的 ClientIDMode 设置。
回答by user2622042
In .NET 4+ set ClientIDMode="Static"
. This will solve your problem.
在 .NET 4+ 中设置ClientIDMode="Static"
. 这将解决您的问题。
Example:
例子:
<asp:Label ID="Label1" ClientIDMode="Static" runat="server" Text="test"></asp:Label>
回答by Crescent Fresh
You can't stop asp.net from generating those IDs. That's just how it does things.
您无法阻止 asp.net 生成这些 ID。这就是它做事的方式。
You can still use jquery like so:
你仍然可以像这样使用 jquery:
$('#<%=label1.ClientID %>').html(xml)
or
或者
$('[id$=_label1]').html(xml)
回答by Russ Cam
Ifand only ifyou're container layout is never going to change andyou require to put your JavaSctipt/jQuery in an external file, you could use the generated ids within your jQuery selectors i.e.
如果和仅当你容器布局是永远不会改变和你需要把你的JavaSctipt / jQuery的一个外部文件,你可以在你的jQuery选择即使用生成的ID
$('#ctl00_ContentPlaceHolder1_Label3').html(xml);
Obviously, this approach requires you to find out what the generated ids will be and requires caution if you ever start changing the site/application construction.
显然,这种方法要求您找出生成的 id 是什么,并且在您开始更改站点/应用程序构造时需要谨慎。
Otherwise, your bestoptions are
否则,你最好的选择是
1.Use the inline server side code markup. The downside to this approach is that you cannot put your js code in an external file -
1.使用内联服务器端代码标记。这种方法的缺点是你不能把你的 js 代码放在一个外部文件中 -
$('#<%= Label3.ClientID %>').html(xml);
2.Define unique CSS classes on each control you need to use in your jQuery, which would still allow you to put your js code in an external file -
2.在需要在 jQuery 中使用的每个控件上定义唯一的 CSS 类,这仍然允许您将 js 代码放在外部文件中 -
<asp:Label ID="Label3" runat="server" Text="test" CssClass="label3">
</asp:Label>
$('.label3').html(xml);
3.Use jQuery selectors to pattern match the original id, which again, would allow you to put your js code in an external file -
3.使用 jQuery 选择器模式匹配原始 id,这再次允许您将 js 代码放在外部文件中 -
$('[id$=Label3]').html(xml);
This jQuery selector will select all elements with attribute idwhose value ends with Label3. The only potential downside that I could see with this approach is that in theory, it could be possible to have a Label control with id Label3 in say, a Master page and also in two content pages. In this example, using the jQuery selector above would match all three labels, which may have unwanted consequences.
这个 jQuery 选择器将选择属性id值以Label3结尾的所有元素。我可以看到这种方法的唯一潜在缺点是,理论上,可以有一个 ID 为 Label3 的 Label 控件,比如在母版页和两个内容页中。在此示例中,使用上面的 jQuery 选择器将匹配所有三个标签,这可能会产生不必要的后果。
EDIT:
编辑:
I thought it might be useful to raise your attention to the IDOverride control. An Example page can be found here
我认为引起您对IDOverride 控件的关注可能会有所帮助。一个例子页面可以在这里找到
It allows you to specify which controls should have their mangled id within the outputted HTML markup overridden with the id as is given in the .aspx file when rendering out the HTML page. I have only played with it briefly with a single Master Page and Panels, but it appears to work well. Using this, you could use the original ids within your jQuery selectors. Be aware however, that the results are unpredictable if you were to have controls with the same ids in your Master page(s) and Content page(s) that are combined to render the HTML for one page.
它允许您指定哪些控件应该在输出的 HTML 标记中使用其损坏的 id 替换为 .aspx 文件中在呈现 HTML 页面时给出的 id。我只用一个母版页和面板简要地玩过它,但它似乎运行良好。使用它,您可以在 jQuery 选择器中使用原始 ID。但是请注意,如果您的母版页和内容页中的控件具有相同的 id,这些控件组合在一起呈现一个页面的 HTML,则结果是不可预测的。
回答by Notorious2tall
Short answer, don't worry about using the asp.net IDs. In asp.net you can add your own attribute to a tag:
简短的回答,不要担心使用 asp.net ID。在 asp.net 中,您可以将自己的属性添加到标签中:
<asp:TexBox ID="myTBox" runat="server" MyCustomAttr="foo" />
Then in jquery you can refer to this element via:
然后在 jquery 中,您可以通过以下方式引用此元素:
$("input[MyCustomAttr='foo']")
I do this all the time with jQuery. Hope it helps.
我一直用 jQuery 来做这件事。希望能帮助到你。
回答by mrbengi
You can call a class name rather than using an ID
您可以调用类名而不是使用 ID
For example;
例如;
$('.CssClassName'). ...
Or if you type this in the MasterPage's very first line, your control IDs won't change :
或者,如果您在 MasterPage 的第一行中键入此内容,您的控件 ID 将不会更改:
ClientIDMode="Static"
ClientIDMode="Static"
For example;
例如;
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="Main_MasterPage" ClientIDMode="Static" %>
回答by Matthew M. Osborn
The inline code is the correct way to do it. However this will be changing in ASP.NET 4.0. We have spent some time adding a feature that allows full control of the IDs that are generated client side. Below are some resources on the web about this feature.
内联代码是正确的方法。然而,这将在 ASP.NET 4.0 中改变。我们花了一些时间添加了一项功能,该功能允许完全控制客户端生成的 ID。以下是网络上有关此功能的一些资源。
回答by CMPalmer
Most of the suggestions here will work, but test results on jQuery code show that pure ID selectors are by far the fastest. The one I use most often:
这里的大部分建议都可以使用,但对 jQuery 代码的测试结果表明,纯 ID 选择器是迄今为止最快的。我最常用的一种:
$("[id$=origControlId]")
is pretty slow, but the problem isn't too apparent unless the page has many controls and a lot of jQuery.
很慢,但除非页面有很多控件和很多 jQuery,否则问题不会太明显。
Since is it fairly painless to assign multiple classes to a control, you could give each one a CSSClass that matches the ID. Since they would then be unique (you'll have to watch repeater type controls that generate multiple controls), you could select by class.
由于将多个类分配给一个控件相当容易,您可以为每个类指定一个与 ID 匹配的 CSSClass。由于它们将是唯一的(您必须查看生成多个控件的中继器类型控件),因此您可以按类进行选择。
For example:
例如:
<asp:Label ID="Label1" CssClass="Label1 SomeOtherClass" runat="server" Text="test">
</asp:Label>
could be selected uniquely by:
可以通过以下方式唯一选择:
$(".Label1")
Which is almostas fast as an ID select.
这几乎和 ID 选择一样快。
I had never considered this one:
我从来没有考虑过这个:
$('#<%= Label1.ClientID %>')
but I'm going to try it!
但我要试试!
回答by devio
You have to pass the control's ClientID to the javascript code (I doubt though that Label1 gets renamed to Label3)
您必须将控件的 ClientID 传递给 javascript 代码(我怀疑 Label1 是否已重命名为 Label3)
ClientScriptManager.RegisterClientScriptBlock(GetType(), "someKey",
"$('#" + Label1.ClientID + "').html(xml);", true);