我想知道下面两个代码片段有什么区别:
<label>Input here : </label>
<input type='text' name='theinput' id='theinput'/>
and
<label for='theinput'>Input here : </label>
<input type='text' name='theinput' id='theinput'/>
我相信当您使用特殊的JavaScript库时,它会做一些事情,但除此之外,它是否验证HTML或出于其他原因需要?
The for attribute associates the label with a control element, as defined in the description of label in the HTML 4.01 spec. This implies, among other things, that when the label element receives focus (e.g. by being clicked on), it passes the focus on to its associated control. The association between a label and a control may also be used by speech-based user agents, which may give the user a way to ask what the associated label is, when dealing with a control. (The association may not be as obvious as in visual rendering.)
在问题的第一个例子中(没有for),标签标记的使用没有逻辑或功能含义-它是无用的,除非您在CSS或JavaScript中使用它。
HTML规范没有强制要求将标签与控件相关联,但是Web内容可访问性指南(WCAG) 2.0要求。这在技术文档H44中有描述:使用标签元素将文本标签与表单控件关联,这也解释了隐式关联(通过嵌套,例如在标签内输入)不像通过for和id属性的显式关联那样得到广泛支持。
The for attribute associates the label with a control element, as defined in the description of label in the HTML 4.01 spec. This implies, among other things, that when the label element receives focus (e.g. by being clicked on), it passes the focus on to its associated control. The association between a label and a control may also be used by speech-based user agents, which may give the user a way to ask what the associated label is, when dealing with a control. (The association may not be as obvious as in visual rendering.)
在问题的第一个例子中(没有for),标签标记的使用没有逻辑或功能含义-它是无用的,除非您在CSS或JavaScript中使用它。
HTML规范没有强制要求将标签与控件相关联,但是Web内容可访问性指南(WCAG) 2.0要求。这在技术文档H44中有描述:使用标签元素将文本标签与表单控件关联,这也解释了隐式关联(通过嵌套,例如在标签内输入)不像通过for和id属性的显式关联那样得到广泛支持。
<label>标记允许您单击标签,它将被视为单击相关的输入元素。有两种方法可以创建这种关联:
一种方法是将label元素环绕在input元素周围:
<label>Input here:
<input type='text' name='theinput' id='theinput'>
</label>
另一种方法是使用for属性,给它相关输入的ID:
<label for="theinput">Input here:</label>
<input type='text' name='whatever' id='theinput'>
这对于复选框和按钮特别有用,因为这意味着您可以通过单击相关文本来选中复选框,而不必点击复选框本身。
在MDN上阅读更多关于<label>元素的信息。
将文本与输入相关联对于可访问性非常重要,因为它为输入提供了可访问的名称,因此辅助技术可以将其提供给残疾用户。屏幕阅读器将在用户聚焦输入时读取标签文本。你也可以让你的语音命令软件聚焦输入,但它需要一个(可见的)名字。
阅读更多关于易用性的信息