What is the difference between readonly=“true” & readonly=“readonly”?
之间有什么区别?
1 | <input name="TextBox1" type="text" id="TextBox1" readonly="true" /> |
和:
1 | <input name="TextBox1" type="text" id="TextBox1" readonly="readonly" /> |
当我将
给元素赋予属性
建议使用W3C标准,即
这是属性设置,而不是有价值的属性
这些属性设置是每次查看的值,不需要对其进行任何分配。存在它们时,元素的布尔属性设置为
1 | <input type="text" readonly /> |
实际上,浏览器对它们的价值分配持开放态度。如果为它们分配任何值,它将被忽略。浏览器将仅看到特定属性的存在,而忽略您尝试分配给它们的值。
这当然很好,因为某些框架无法在不提供其值的情况下添加此类属性。 Asp.net MVC HTML帮助器就是其中之一。 jQuery在1.6版之前一直是相同的,他们添加了属性的概念。
当然,还有一些与XHTML相关的含义,因为XML中的属性需要值才能形成正确的格式。但这是一个不同的故事。因此,浏览器必须忽略值分配。
无论如何。只要名称正确拼写,就可以为浏览器检测到,不用担心您为它们分配的值。但是为了提高可读性和可维护性,最好为它们分配有意义的值,例如:
1 2 | readonly="true" <-- arguably best human readable readonly="readonly" |
相对于
1 2 | readonly="johndoe" readonly="01/01/2000" |
这可能会使将来的开发人员难以维护您的代码,并可能干扰将来的规范,后者可能会为此类属性设置定义更严格的规则。
HTML5规范:
http://www.w3.org/TR/html5/forms.html#attr-input-readonly:
The readonly attribute is a boolean attribute
http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes:
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.
结论:
以下是有效,等效和正确的内容:
1 2 3 4 | <input type="text" readonly /> <input type="text" readonly="" /> <input type="text" readonly="readonly" /> <input type="text" readonly="ReAdOnLy" /> |
以下是无效的:
1 2 3 4 | <input type="text" readonly="0" /> <input type="text" readonly="1" /> <input type="text" readonly="false" /> <input type="text" readonly="true" /> |
该属性的缺失是false的唯一有效语法:
1 | <input type="text"/> |
建议
如果您关心编写有效的XHTML,请使用
如果您的文档类型是xhtml过渡文档或严格文档,并且您想对其进行验证,请使用
我不确定它们在功能上有何不同。我当前的OS X浏览器批次没有任何区别。
由于传统的HTML属性处理,我认为它们在功能上都是相同的。回想一下,任何标记(布尔)属性仅需存在,但不带值,例如
1 2 | <input readonly> <option selected> |
当XHTML出现时,此语法无效,并且需要值。虽然W3使用属性名称作为值来指定,但我猜想大多数浏览器供应商都决定只检查属性是否存在。
根据HTML标准,使用
1 | <input name="TextBox1" type="text" id="TextBox1" readonly/> |
足以使输入元素变为只读。但是,XHTML标准指出,由于
https://www.w3.org/TR/xhtml1/diffs.html#h-4.5
http://www.w3schools.com/tags/att_input_readonly.asp