如果元素被标签包裹,标签是否需要 "for" 属性?

If an element is wrapped by a label, does the label require the "for" attribute?

假设我有一套收音机 <input>。我不是穴居人,所以我知道我需要将 <label> 与那些 <input> 联系起来。我喜欢将单选按钮包装在相应的标签中,例如 reasons enumerated here.

因此,例如:

<fieldset>
    <legend>Should I provide a "for" attribute?</legend>
    <label><input type="radio" name="define_the_for_attribute" id="define_the_for_attribute_yes" value="yes" />Yep, if you know what's good for you</label>
    <label><input type="radio" name="define_the_for_attribute" id="define_the_for_attribute_no" value="no" />Nah, that would be redundant and repetitive</label>
</fieldset>

此包装将相应的单选按钮与标签相关联。我需要定义标签的for属性吗?

<fieldset>
    <legend>Should I provide a "for" attribute?</legend>
    <label for="define_the_for_attribute_yes"><input type="radio" name="define_the_for_attribute" id="define_the_for_attribute_yes" value="yes" />Yep, if you know what's good for you</label>
    <label for="define_the_for_attribute_no"><input type="radio" name="define_the_for_attribute" id="define_the_for_attribute_no" value="no" />Nah, that would be redundant and repetitive</label>
</fieldset>

As pointed out by @Peter, "The for attribute of the label element must refer to a form control" (see http://www.w3.org/TR/html-markup/label.html), 但这可以理解为 "if you specify the optional for attribute, it must refer to a valid form control".

根据 HTML5 规范 - "If the for attribute is not specified, but the label element has a labelable element descendant, then the first such descendant in tree order is the label element's labeled control."

http://www.w3.org/TR/html5/forms.html#category-label

所以基本上,只要包装这些元素中的任何一个,就不需要它:按钮、输入(如果类型属性不处于隐藏状态)、keygen、meter、output、progress、select,或文本区域

根据规范,当控件元素包含在 label 元素中时,您不需要 for 属性。这一原则也适用于所有现代浏览器,尽管一些非常旧的 IE 版本仅支持与 for 属性的显式关联。

出于逻辑原因,人们可能仍然更喜欢使用 for 属性:控件在逻辑上不是标签的一部分,因此它应该放在标签之外。然后你需要 for 属性才能从 label 标记中受益。

当控件不能label元素的后代时,for属性是必需的,例如当您在 table 元素的一列中有标签时,在另一列中有控件。