Why use the “for” keyword to bind a label in HTML?

2020-02-17 08:54发布

Possible Duplicate:
What is the For attribute for in an HTML tag?

I have been trying to find this out. What is the reason for using the "for=" when you use a label in HTML?

<form>
  <label for="male">Male</label>
  <input type="radio" name="sex" id="male" />
  <br />
  <label for="female">Female</label>
  <input type="radio" name="sex" id="female" />
</form>

If it's needed then is there some equivalent in HTML 5 or is it the same?

标签: html
3条回答
来,给爷笑一个
2楼-- · 2020-02-17 09:03

If you use the for attribute of the label, and set its value to the id of a related input element, most browsers will focus the input element when the label is clicked on. This is especially useful for small elements like checkboxes and radio buttons.

查看更多
▲ chillily
3楼-- · 2020-02-17 09:30

It makes a click on the label focus the input element it is for.

In the example you posted, you simply click on the word Male or the radio button in order for it to get selected. Without this, you have a much smaller target to click...

If it's needed then is there some equivalent in HTML 5 or is it the same?

It is not required, but is good practice for labels that have a direct form element to focus on (it wouldn't make much sense for a label that doesn't have a counterpart on a form).

The syntax is the same for HTML 5.

查看更多
够拽才男人
4楼-- · 2020-02-17 09:30

For binds the <label> and the <input> field together. for should point to the id of the <input>. It is not actually needed, but it is useful for example on radio buttons, where the user can click the label to check the radio button, thus creating a larger click area and a better user experience.

You use for the same in way HTML5 as you do in HTML4 or XHTML or whatever you used before.

查看更多
登录 后发表回答