我想知道下面两个代码片段有什么区别:

<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或出于其他原因需要?


当前回答

它为for属性的参数标记任何输入。

<input id='myInput' type='radio'> <label for='myInput'>我的第一个Radio label </label> < br > <input id='input2' type='radio'> <label for='input2'>My 2nd Radio label </label> < br > <input id='input3' type='radio'> <label for='input3'>My 3rd Radio label </label>

其他回答

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属性的显式关联那样得到广泛支持。

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>

它为for属性的参数标记任何输入。

<input id='myInput' type='radio'> <label for='myInput'>我的第一个Radio label </label> < br > <input id='input2' type='radio'> <label for='input2'>My 2nd Radio label </label> < br > <input id='input3' type='radio'> <label for='input3'>My 3rd Radio label </label>

简而言之,它所做的就是引用输入的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">

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