在freecodecamp上HTML教程的Create a Set of Radio Buttons
这一节中,看到这样一段话,php
It is considered best practice to set afor
attribute on thelabel
element, with a value that matches the value of theid
attribute of theinput
element. This allows assistive technologies to create a linked relationship between the label and the childinput
element.
大概的意思是:最好的作法,是给label
标签,添加for
属性,其值与input
标签的id
属性的值相同,以在label和input之间建立关联。html
同时,给出一段示例代码,以下:ide
<!-- Code 1 --> <label for="indoor"> <input id="indoor" type="radio" name="indoor-outdoor">Indoor </label>
代码中,label
的for
属性值与input
的id
属性值相同。从这段代码中,并不能看出关联在何处。即便将for属性删除,运行结果也没有差异。工具
在w3schools上,关于label的for属性的定义以下:spa
The for attribute specifies which form element a label is bound to.
译文:for属性指定label与表单中的哪一个元素进行绑定。
示例代码:code
<!-- Code 2 --> <form action="/action_page.php"> <input type="radio" name="gender" id="male" value="male"> <label for="male">Male</label> <br> <input type="radio" name="gender" id="female" value="female"> <label for="female">Female</label> <br> <input type="radio" name="gender" id="other" value="other"> <label for="other">Other</label> <br> <input type="submit" value="Submit"> </form>
根据w3schools提供的定义和示例代码,能够看出for属性和id属性相同的话,label和input是一一对应的关系。orm
对比两段代码,不难发现,htm
若是,咱们将两段代码中label的for属性删除,上述的第1点和第2点依然成立,变化的是第3点。
Code 1 的运行结果,点击label的文字内容,依旧可以选中单选按钮。由于input包含在label中。而 Code 2 的则不一样,点击label的内容,没法选中单选按钮。教程
通过简单的代码运行结果对比,咱们可以验证文章开头引用的那段话是正确的。为label添加for属性的这个作法,可以提升代码质量。ip