关于 HTML 标签的“ For”属性

考虑到以下两行代码(复制自 w3school. com > “ HTML < label > for Attribute”) :

  <label for="male">Male </label>
<input type="radio" name="sex" id="male" />

我有麻烦发现确切的目的上述标签的“为”属性。正如您所看到的,它当前被设置为“男性”(以匹配输入控件的 id)。

到目前为止,我所读到的只是上面的代码将“关联”和“绑定”标签与输入控件。 所以我的问题是,这到底是什么意思?

将标签关联到输入控件的结果到底是什么?
标签和/或输入是否会因为这种“关联”而产生新的行为?

35468 次浏览

A label that is associated with a control via for will be clickable. Clicking it selects the control. Highly useful with radio/checkboxes in particular. It also has accessibility implications for screen readers for the visually impaired.

When you click on the label (Male), the radio will be checked something not possible if you are not using a label. A label is also useful when developing for small devices such as mobiles.

So, it is useful for:

  • accessibility reasons
  • smaller devices such as mobiles, etc
  • useful in radio buttons and check boxes especially

I believe that linking a label to a form element allows you to assign the label an access key, which will bring the focus to the form element associated with it.

As others have mentioned it also allows you to click on the label and bring focus to the form element.

The for attribute alllows you to place the label and the element in semantically different areas of the html, and maintain association. (Like two tables, or two different divs). If you're putting both of them together like in your example, it is also correct to enclose the form element in the label and forgo the for attribute

Yes, I believe it acts as a form control or a check mechanism when filling a form on webpage, especially ones with radio buttons or check boxes. By clicking on the label, it points the user directly to an area on the form where the right information should be typed. For example, a "text." Or, in a case where the user must choose from some options, such as true or false, or male or female.