“为"是什么意思?HTML 中的属性 do <label>标签? [英] What does &quot;for&quot; attribute do in HTML &lt;label&gt; tag?

查看:42
本文介绍了“为"是什么意思?HTML 中的属性 do <label>标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道以下两个代码片段有什么区别:

I wonder what is the difference between the following two code snippets:

<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 或出于其他原因需要?

I'm sure it does something when you use a special JavaScript library, but apart from that, does it validate the HTML or required for some other reason?

推荐答案

标签允许你点击标签,它会被当作点击相关的输入元素.有两种方法可以创建此关联:

The <label> tag allows you to click on the label, and it will be treated like clicking on the associated input element. There are two ways to create this association:

一种方法是将标签元素包裹在输入元素周围:

One way is to wrap the label element around the input element:

<label>Input here:
    <input type='text' name='theinput' id='theinput'>
</label>

另一种方法是使用 for 属性,给它关联输入的 ID:

The other way is to use the for attribute, giving it the ID of the associated input:

<label for="theinput">Input here:</label>
<input type='text' name='whatever' id='theinput'>

这对于与复选框和按钮一起使用特别有用,因为这意味着您可以通过单击相关文本来选中该框,而不必点击该框本身.

This is especially useful for use with checkboxes and buttons, since it means you can check the box by clicking on the associated text instead of having to hit the box itself.

MDN 中阅读有关此元素的更多信息.

Read more about this element in MDN.

这篇关于“为"是什么意思?HTML 中的属性 do <label>标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆