如果元素由标签包裹,则标签是否需要“ for”标签?属性? [英] If an element is wrapped by a label, does the label require the "for" attribute?

查看:112
本文介绍了如果元素由标签包裹,则标签是否需要“ for”标签?属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一组收音机< input> s。我不是穴居人,所以我知道我需要将< label> 与那些< input> s。我喜欢将单选按钮包装在相应的标签内,以此处列举的原因

Say I have a set of radio <input>s. I'm not a caveman, so I know I need to associate <label> with those <input>s. I'm fond of wrapping the radio buttons within their corresponding labels, for 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 属性?

This wrapping associates the corresponding radio button with the label. Do I also need to define the label's for attribute?

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

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

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), but this could be read to mean "if you specify the optional for attribute, it must refer to a valid form control".

推荐答案

根据HTML5规范-如果未指定for属性,但是label元素具有可标记的元素后代,则树顺序中的第一个此类后代就是标签元素的标签控件。

According to the HTML5 spec - "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

因此,基本上,不需要,只要它包装了以下任何元素:按钮,输入(如果type属性未处于隐藏状态),键源,仪表,输出,进度,选择或文本区域

So basically, no it is not required as long as it is wrapping any of these elements: button, input (if the type attribute is not in the hidden state), keygen, meter, output, progress, select, or textarea

这篇关于如果元素由标签包裹,则标签是否需要“ for”标签?属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆