什么时候应该使用标签元素?

时间:2013-09-28 13:50:45

标签: html html5

我正在学习一些HTML而且我对label元素的使用感到困惑,因为我在许多地方找到它,表单中有输入,optgroup标记用于select部分1}}元素,在textarea元素之前等等。

那么,是否有规则何时使用它以及何时避免以错误的方式使用它?特别是在HTML5中?

4 个答案:

答案 0 :(得分:1)

  

标签:此属性显式将正在定义的标签与另一个控件相关联。

因此,当您要为文本框,复选框等其他控件显示某些文本或标签时,应使用label属性。

重要的是

  

如果存在,则此属性的值必须与同一文档中某个其他控件的id属性的值相同。如果不存在,则定义的标签与元素的内容相关联。

Look at here for the documentation

答案 1 :(得分:1)

<label>元素应与表单字段一起使用:大多数类型的<input><select><textarea>。如果for属性包含相关元素的id。因此,如果单击标签,则会关注相关元素。

Example Usage at Jsbin

<label for="textinput">Enter data here</label>
<input id="textinput>"

<input type="checkbox" id="checkbox">
<label for="checkbox">What this box does</label>

<input type="radio" id="radio_opt1" name="radiogroup">
<label for="radio_opt1">Option description</label>
<input type="radio" id="radio_opt2" name="radiogroup">
<label for="radio_opt2">Option description</label>

<label for="select">Select an option</label>
<select id="select">
    <option>Some option</option>
</select>

<label for="textarea">Enter data into the textarea</label>
<textarea id="textarea"></textarea>

<optgroup>元素中,有一个label属性,它与标签元素不同,尽管它的功能类似:识别某组选项:

<select>
    <optgroup label="First group">
        <option>Some option</option>
    </optgroup>
    <optgroup label="First group">
        <option>Some option</option>
    </optgroup>
</select>

答案 2 :(得分:0)

不,这不是HTML5独家:)

Label可以与<input>, <select>, <textarea>等表单元素结合使用。单击标签会自动将焦点更改为连接元素。

将标签与元素连接有两种方式:

  1. 将元素置于标签
  2. 为标签添加for属性,其中for值为id的元素需要连接
  3. 示例(摘自http://htmlbook.ru/html/label):

    <!DOCTYPE HTML>
    <html>
     <head>
      <meta charset="utf-8">
      <title>LABEL</title>
     </head>
     <body>
      <form action="handler.php">
       <p><b>Lorem ipsum dolor sit amet...</b></p>
       <p><input type="checkbox" id="check1"><label for="check1">Lorem</label><Br>
       <input type="checkbox" id="check2"><label for="check2">Ipsum</label><Br>
       <input type="checkbox" id="check3"><label for="check3">Dolor</label><Br>
       <input type="checkbox" id="check4"><label for="check4">Sit amet</label></p>
      </form> 
     </body>
    </html>
    

答案 3 :(得分:-1)

它应该与其他元素一起使用。它可以在现有表单控件之前,之后或周围。 以下是W3Schools的示例。

<form action="demo_form.asp">
  <label for="male">Male</label>
  <input type="radio" name="sex" id="male" value="male"><br>
  <label for="female">Female</label>
  <input type="radio" name="sex" id="female" value="female"><br>
  <input type="submit" value="Submit">
</form>
相关问题