I would expect this:

<asp:CheckBox    ID="CheckBox1"    runat="server" CssClass="myClass" />
<asp:RadioButton ID="RadioButton1" runat="server" CssClass="myClass" />
<asp:TextBox     ID="TextBox1"     runat="server" CssClass="myClass" />

...to render like this (with some attributes removed for simplicity):

<input id="CheckBox1"    type="checkbox" class="myClass" />
<input id="RadioButton1" type="radio"    class="myClass" />
<input id="TextBox1"     type="text"     class="myClass" /> 

...when in fact, the RadioButton and CheckBox get wrapped with a span tag and the CSS class gets applied there.

<span class="myClass"><input id="CheckBox1"    type="checkbox" /></span> 
<span class="myClass"><input id="RadioButton1" type="radio"    /></span> 
<input type="text" id="TextBox1" class="myClass" /> 

Is there a reason for this and is there a way to avoid it? It makes jQuery selectors ugly since you can't catch all of them with:

$("input.myClass")

Granted it is just going to:

$("input.myClass, span.myClass input")

...but that is ugly. I could write my own selector, but again not as elegant as it should be.

推荐答案

Web controls in the System.Web.UI.WebControls namespace may render differently in different browsers. You can't count on them rendering the same elements always. They may add anything that they think is needed to make it work in the specific browser.

If you want to have any control over how the controls are rendered as html, you should use the controls in the System.Web.UI.HtmlControls namespace instead. That is:

<input type="checkbox" id="CheckBox1" runat="server" class="myClass" />
<input type="radio" name="RadioButton1" runat="server" class="myClass" />
<input type="text" id="TextBox1" runat="server" class="myClass" />

They will render just as the corresponding html element, with no extra elements added. This of course means that you will have to take responsibility for the browser compatibility, as the control doesn't. Also, those controls doesn't have all the features of the controls in the WebControls namespace.

Asp.net相关问答推荐

AJAX返回未定义、失败

$(document).ready 不工作

在每个对象上设置 ClientIDMode = Static 是否有任何缺点(在母版页的 maincontent 上设置)

ASP.NET @Register 与 @Reference

如何异步渲染局部视图

如何从 web.config 中读取系统值并在 ASP.NET MVC C# 方法中使用

IIS 7.5 上没有 asp.net 功能

为什么aspx文件会返回404(找不到页面)

ASP.net 与 PHP( Select 什么)

如何在 ASP.NET 下拉列表中添加选项组?

SimpleMembership 与 ASP.NET MVC 4 中的自定义数据库架构

如何配置 ELMAH 以使用 Windows Azure?我在 Elmah.axd 上得到 404

MVC5 身份验证中的......与主域之间的信任关系失败

如何针对异常需求自定义 ASP.NET Web API AuthorizeAttribute

在 Android/Java 和 C# 中计算 SHA256 哈希

.NET AJAX 调用 ASMX 或 ASPX 或 ASHX?

将当前谷歌 map 保存为图片

Windows Azure PaaS(网络角色)的真正替代品?

解耦 ASP.NET MVC 5 标识以允许实现分层应用程序

为什么 C# 对于 CSC 文件会遇到此错误?