“for”属性在HTML <label>标记中的作用是什么?我想知道以下两个代码片段之间的区别是什么:<label>Input here : </label><input type='text' name='theinput' id='theinput'/>和<label for='theinput'>Input here : </label><input type='text' name='theinput' id='theinput'/>我确定当你使用一个特殊的JavaScript库时它会有所作为,但除此之外,它是否验证HTML或其他原因需要?
3 回答

慕田峪4524236
TA贡献1875条经验 获得超5个赞
该<label>
标签可让您单击标签,它会像单击相关的输入元素上进行处理。有两种方法可以创建此关联:
一种方法是将label元素包装在input元素周围:
<label>Input here: <input type='text' name='theinput' id='theinput'></label>
另一种方法是使用该for
属性,为其提供相关输入的ID:
<label for="theinput">Input here:</label><input type='text' name='whatever' id='theinput'>
这对于使用复选框和按钮特别有用,因为这意味着您可以通过单击相关文本来检查框,而不必单击框本身。
在MDN中阅读有关此元素的更多信息。

慕尼黑8549860
TA贡献1818条经验 获得超11个赞
该for
属性将标签与控件元素相关联,如label
HTML 4.01规范中的描述中所定义。除其他事项外,这意味着当label
元素获得焦点时(例如,通过单击),它将焦点传递给其关联的控件。标签和控件之间的关联也可以由基于语音的用户代理使用,这可以在处理控件时向用户提供询问相关标签是什么的方式。(该关联可能不像在视觉渲染中那么明显。)
在问题的第一个例子中(没有for
),label
标记的使用没有逻辑或功能含义 - 它是无用的,除非你用CSS或JavaScript做一些事情。
HTML规范并不强制要求将标签与控件相关联,但Web内容可访问性指南(WCAG)2.0也是如此。这在技术文档H44中描述:使用标签元素将文本标签与表单控件相关联,这也解释了隐式关联(通过例如input
内部嵌套label
)不像显式关联via for
和id
attributes 那样得到广泛支持,

Helenr
TA贡献1780条经验 获得超4个赞
简而言之它的作用是指id
输入,这就是全部:
<label for="the-id-of-the-input">Input here:</label><input type="text" name="the-name-of-input" id="the-id-of-the-input">
- 3 回答
- 0 关注
- 576 浏览
相关问题推荐
添加回答
举报
0/150
提交
取消