我想知道下面两个代码片段有什么区别:
<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属性的显式关联那样得到广泛支持。