HTML <label>标记中的“ for”属性有什么作用?

我想知道以下两个代码段之间的区别是什么:

<label>Input here : </label>
<input type='text' name='theinput' id='theinput'/>

<label for='theinput'>Input here : </label>
<input type='text' name='theinput' id='theinput'/>

我确定当您使用特殊的JavaScript库时,它会执行某些操作,但是除此之外,它是否可以验证HTML或出于其他原因而需要?

乐米亚2020/03/23 14:14:38

简而言之,它所做的就是引用id输入的,仅此而已

<label for="the-id-of-the-input">Input here:</label>
<input type="text" name="the-name-of-input" id="the-id-of-the-input">
小小TomNear2020/03/23 14:14:38

<label>标签的for属性应等于相关元素的id属性,以将它们绑定在一起。

宝儿理查德2020/03/23 14:14:38

for属性显示此标签代表相关的输入字段,复选框或单选按钮或与其关联的任何其他数据输入字段。例如

    <li>
<label>{translate:blindcopy}</label>
            <a class="" href="#" title="{translate:savetemplate}" onclick="" ><i class="fa fa-list" class="button" ></i></a> &nbsp 
            <input type="text" id="BlindCopy" name="BlindCopy" class="splitblindcopy" />
    </li>
老丝2020/03/23 14:14:38

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.)

In the first example in the question (without the for), the use of label markup has no logical or functional implication – it’s useless, unless you do something with it in CSS or JavaScript.

HTML规范没有强制性要求将标签与控件关联,但是Web内容可访问性指南(WCAG)2.0确实如此。在技​​术文档H44:使用标签元素将文本标签与表单控件相关联中对此进行了描述,该文档还解释了隐式关联(通过嵌套,例如inputinside label)不如通过forid属性的显式关联得到广泛支持