1

我发现了一些奇怪的行为,我想知道是否有人可以在这里提供帮助。

我正在使用继承 addAttribute 方法的 XhtmlTextWriter 类创建一个表单。我正在创建一个input需要漂亮(HTML5)占位符属性的标签。该addAttribute方法有两个参数:属性名称和值。属性名称可以从HtmlTextWriteAttribute枚举中选取,也可以作为字符串手动输入。由于枚举中没有“占位符”,因此我使用了以下代码:

StringWriter sw = new StringWriter();
XhtmlTextWriter html = new XhtmlTextWriter(sw);
html.AddAttribute(HtmlTextWriterAttribute.Type, "text");
html.AddAttribute(HtmlTextWriterAttribute.Name, "firstname");
html.AddAttribute("placeholder", "First Name");
html.AddAttribute("maxlength", "25");
html.RenderBeginTag(HtmlTextWriterTag.Input);
html.RenderEndTag();//input
return sw.ToString();

这很好地创建了指定的元素和属性...除了占位符:

<input type="text" name="firstname" maxlength="25"></input>

有谁知道我的占位符在哪里?(如您所见maxlength,使用字符串作为属性名称是可行的......)

注意:这确实有效,但并不那么漂亮:

html.WriteBeginTag("input"); 
html.WriteAttribute("type", "text");
html.WriteAttribute("placeholder", "First Name");
html.Write(HtmlTextWriter.SelfClosingTagEnd);

// 更新:属性有同样的问题required...可能是 HTML5 特定的东西吗?

4

1 回答 1

3

这是因为您使用XhtmlTextWriter的是 ,它的属性非常严格,不会写出无法识别的属性(因为需要生成有效的 XHTML)。你有两个选择。

一:改用HtmlTextWriter

HtmlTextWriter html = new HtmlTextWriter(sw);

二:如果XhtmlTextWriter由于某种原因需要使用,可以在将属性添加到元素之前添加placeholder为元素的可识别属性:input

html.AddRecognizedAttribute("input", "placeholder");
于 2014-05-21T20:25:33.753 回答