是“为了”如果目标输入嵌套在标签内,HTML 标签中是否需要属性?
我注意到,当您将输入元素放入标签元素时,HTML 标签标记不需要“for”属性:
<label><input type="text">Last name</label>
但我想知道最佳实践是什么。有人可以帮我吗?
谢谢!
I've noticed that a HTML label tag doesn't need the 'for' attribute when you put your input element into the label element:
<label><input type="text">Last name</label>
But I was wondering what's the best practise. Can anybody help me with that?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它用于屏幕阅读器等的辅助功能,即
use_the_label_element_to_make_your_html_forms_accessible
所以你应该使用它。这里有一个链接,可以让您了解可访问性的重要性。
这里有一个小故事 - 让您的网站无障碍可以让所有用户受益 - 我一直对市政当局为轮椅无障碍所付出的努力感到惊讶,直到我有了一个女儿并使用婴儿车。我认为网站遵循同样的规则——每个人都受益。
为争论道歉
It's used for accessibility for screen readers and the like i.e.
use_the_label_element_to_make_your_html_forms_accessible
So you should use it. And here is a link to convince you about the importance of accessibily.
And here is a little story - making your site accessible can benefit all users - i always was amazed at the amount of effort civic authorities went to for wheelchair accessibilty until I had a daughter and use a push chair. I think websites follow the same rule - everyone benefits.
Apologies for the polemic
W3 HTML 5.2 标准 和WhatWG Living Standard 状态(几乎准确地说,引用来自后者):
因此,就遵循 HTML 标准而言,这样使用是可以的。
Both the W3 HTML 5.2 standard and the WhatWG Living Standard state (in almost exact terms, quote is from the latter):
So it's okay to use it that way in terms of following the HTML standard.
for 属性对于文本输入没有太大区别,但对于复选框输入非常有用,因为它允许用户单击标签以及复选框本身:
The for attribute doesn't make much difference with a text input, but is very useful with a checkbox input, as it allows users to click on the label as well as the checkbox itself:
您可以将
input
包含在您的label
中,并将其与label
关联,或者如果由于某种原因您必须拥有您的label
元素位于 DOM 中的其他位置,您可以使用for
属性指定其含义。不管怎样,使用for
属性总是没有坏处的:)You can include the
input
in yourlabel
and it is associated with thelabel
, or if for some reason you have to have yourlabel
element elsewhere in the DOM, you can specify it's meaning with thefor
attribute. It never hurts to use thefor
attribute though either way :)