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

Jer*_*nch 5 html accessibility section508

说我有一套收音机<input>.我不是一个穴居人,所以我知道我需要<label>与那些人<input>交往.由于这里列举原因,我喜欢将单选按钮包装在相应的标签内.

所以,例如:

<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>
Run Code Online (Sandbox Code Playgroud)

此包装将相应的单选按钮与标签相关联.我需要定义标签的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>
Run Code Online (Sandbox Code Playgroud)

正如指出@Peter说:"为标签元素的属性必须引用表单控件"(见http://www.w3.org/TR/html-markup/label.html),但是这可以被理解表示"如果指定可选for属性,则必须引用有效的表单控件".

小智 8

根据HTML5规范 - "如果未指定for属性,但label元素具有可变元素后代,则树序中的第一个这样的后代是标签元素的标记控件."

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

所以基本上,只要它包装任何这些元素就不需要它:按钮,输入(如果type属性不处于隐藏状态),keygen,meter,output,progress,select或textarea