为什么使用“for”关键字来绑定 HTML 中的标签?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10813592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why use the "for" keyword to bind a label in HTML?
提问by Alan2
Possible Duplicate:
What is the For attribute for in an HTML tag?
可能的重复:
HTML 标记中的 For 属性是什么?
I have been trying to find this out. What is the reason for using the "for=" when you use a label in HTML?
我一直试图找出这一点。在 HTML 中使用标签时使用“for=”的原因是什么?
<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 5 中是否有一些等价物或相同?
回答by Oded
It makes a click on the label focus the input element it is for
.
它使点击标签聚焦它的输入元素for
。
In the example you posted, you simply click on the word Male
orthe radio button in order for it to get selected. Without this, you have a much smaller target to click...
在您发布的示例中,您只需单击单词Male
或单选按钮即可将其选中。没有这个,你点击的目标要小得多......
If it's needed then is there some equivalent in HTML 5 or is it the same?
如果需要,那么 HTML 5 中是否有一些等价物或相同?
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.
语法与 HTML 5 相同。
回答by Nix
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.
For 将<label>
和<input>
字段绑定在一起。for
应该指向id
的<input>
。它实际上不是必需的,但它对于例如单选按钮很有用,用户可以单击标签来检查单选按钮,从而创建更大的单击区域和更好的用户体验。
You use for
the same in way HTML5 as you do in HTML4 or XHTML or whatever you used before.
您使用for
HTML5 的方式与您在 HTML4 或 XHTML 或之前使用的任何内容中的使用方式相同。
回答by Graham Clark
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.
如果使用for
标签的属性,并将其值设置id
为相关input
元素的 ,大多数浏览器会在点击标签时聚焦输入元素。这对于复选框和单选按钮等小元素特别有用。