在freecodecamp上HTML教程的CreateaSetofRadioButtons这一节中,看到这样一段话,
Itisconsideredbestpracticetosetaforattributeonthelabelelement,withavaluethatmatchesthevalueoftheidattributeoftheinputelement.Thisallowsassistivetechnologiestocreatealinkedrelationshipbetweenthelabelandthechildinputelement.
大概的意思是:最好的做法,是给label标签,添加for属性,其值与input标签的id属性的值相同,以在label和input之间创建关联。
同时,给出一段示例代码,如下:
<!--Code1-->
<labelfor="indoor">
<inputid="indoor"type="radio"name="indoor-outdoor">Indoor
</label>
499006772-5b6aba4e9b8a8_articlex.png
代码中,label的for属性值与input的id属性值相同。从这段代码中,并不能看出关联在何处。
关于label的for属性的定义如下:
Theforattributespecifieswhichformelementalabelisboundto.
译文:for属性指定label与表单中的哪个元素进行绑定。
示例代码:
<!--Code2-->
<formaction="/action_page.php">
<inputtype="radio"name="gender"id="male"value="male">
<labelfor="male">Male</label>
<br>
<inputtype="radio"name="gender"id="female"value="female">
<labelfor="female">Female</label>
<br>
<inputtype="radio"name="gender"id="other"value="other">
<labelfor="other">Other</label>
<br>
<inputtype="submit"value="Submit">
</form>
2064555765-5b6aba13d54a3_articlex.png
对比两段代码,不难发现,
label与input标签的包含关系不同。Code1的label和input,属于包含关系,Code2的label和input相对独立。
label与input在页面上的排列方式不同。通过Chrome的开发者工具不难发现,Code1的运行结果,label标签将input标签遮盖,Code2的运行结果,label标签与input标签并列。
label与input一一对应。点击label的内容,对应的单端按钮都会被选中。
如果,我们将两段代码中label的for属性删除,则之前的第1点和第2点不变,变化的是第3点。Code1的运营结果,点击label的内容,照旧能够选中单选按钮。而Code2的则不同,点击label的内容,无法选中单选按钮。
经过简单的代码运行结果对比,我们能够验证文章开头引用的那段话是正确的。为label添加for属性的这个做法,能够提高代码质量。


本文转载自中文网


本文转载自中文网
如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html5/h54936.shtml