關於的for屬性的簡單探索

freecodecamp上HTML教程的Create a Set of Radio Buttons這一節中,看到這樣一段話,php

It is considered best practice to set a for attribute on the label element, with a value that matches the value of the id attribute of the input element. This allows assistive technologies to create a linked relationship between the label and the child input element.

大概的意思是:最好的作法,是給label標籤,添加for屬性,其值與input標籤的id屬性的值相同,以在label和input之間建立關聯。html

同時,給出一段示例代碼,以下:ide

<!-- Code 1 -->
<label for="indoor"> 
  <input id="indoor" type="radio" name="indoor-outdoor">Indoor 
</label>

Code 1 運行結果

代碼中,labelfor屬性值與inputid屬性值相同。從這段代碼中,並不能看出關聯在何處。即便將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>

Code 2 運行結果

根據w3schools提供的定義和示例代碼,能夠看出for屬性和id屬性相同的話,label和input是一一對應的關係。orm

對比兩段代碼,不難發現,htm

  1. label與input標籤的包含關係不一樣。Code 1 的label和input,屬於包含關係,Code 2 的label和input相對獨立。
  2. label與input在頁面上的排列方式不一樣。經過Chrome的開發者工具(快捷鍵Ctrl + Shift + i)不難發現,Code 1 的運行結果,label標籤將input標籤包含,Code 2 的運行結果,label標籤與input標籤並列。
  3. label與input一一對應。點擊label的內容,對應的單選按鈕都會被選中。

若是,咱們將兩段代碼中label的for屬性刪除,上述的第1點和第2點依然成立,變化的是第3點。
Code 1 的運行結果,點擊label的文字內容,依舊可以選中單選按鈕。由於input包含在label中。而 Code 2 的則不一樣,點擊label的內容,沒法選中單選按鈕。教程

通過簡單的代碼運行結果對比,咱們可以驗證文章開頭引用的那段話是正確的。爲label添加for屬性的這個作法,可以提升代碼質量。ip

相關文章
相關標籤/搜索