【发布时间】:2015-03-10 15:22:30
【问题描述】:
我在 C#/ASP.net 中创建一个新的 HtmlGenericControl,需要在控件上创建一个没有值的属性。这意味着属性后没有 =""。
oHtmlGenericControl = new HtmlGenericControl("MyHtmlTag");
oHtmlGenericControl.Attributes.Add("MyFirstAttribute", "MyAttributeValue");
oHtmlGenericControl.Attributes.Add("MySecondAttribute", "");
会产生这样的东西......
<MyHtmlTag MyFirstAttribute="MyAttributeValue" MySecondAttribute=""></MyHtmlTag >
而我想要的是这个……
<MyHtmlTag MyFirstAttribute="MyAttributeValue" MySecondAttribute></MyHtmlTag >
我尝试传递 null 而不是空字符串,但该属性根本没有出现。
我做了以下思考它一开始就起作用了......
oHtmlGenericControl = new HtmlGenericControl("MyHtmlTag");
oHtmlGenericControl.TagName = oHtmlGenericControl.TagName + " MySecondAttribute";
但它最终给了我这个......
<MyHtmlTag MySecondAttribute></MyHtmlTag MySecondAttribute>
因此,根据 cmets,HTML 中可能没有任何“无价值”的属性。在仔细检查 W3C 标准后,添加我需要添加的属性的正确方法是 AttributeName="AttributeName"。尽管大多数浏览器都接受并认为 AttributeName 本身是有效的,但在大多数在线示例中没有给出值。
oHtmlGenericControl.Attributes.Add("MyAttributeName", "MyAttributeName");
所以上面的例子适用于我的情况(可能是所有类似的情况),但并不能准确回答是否可以使用 HtmlGenericControl 添加没有值的属性。
<MyHtmlTag MyAttributeName="MyAttributeName"></MyHtmlTag>
【问题讨论】:
-
你为什么想要那个? HTML 中确实没有无价值的属性。大多数浏览器都接受它们(例如输入字段中的“禁用”),但这只是它们的语法约定。就 HTML 而言,编写 'disabled="true"' 是编写这些属性的正确方法。
-
@Joonas "checked" 就是一个例子
-
是的,浏览器会正确评估'checked',即使它不是有效的XHTML,但有效的编写方式是checked='checked'。
-
@Joonas 实际上,checked='checked' 的唯一原因是支持 XHTML。它在 HTML 4 和 5 中是一个无价值的属性。
-
@Joonas 你是对的。但我不喜欢假设“为什么”,我喜欢回答这个问题。也许 OP 正在试验 Web Components 什么的。