在freecodecamp上HTML教程的Create a Set of Radio Buttons
這一節(jié)中,看到這樣一段話,
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之間創(chuàng)建關聯(lián)。
同時,給出一段示例代碼,如下:
<!-- Code 1 --> <label for="indoor"> <input id="indoor" type="radio" name="indoor-outdoor">Indoor </label>
代碼中,label的for屬性值與input的id屬性值相同。從這段代碼中,并不能看出關聯(lián)在何處。
關于label的for屬性的定義如下:
The for attribute specifies which form element a label is bound to.示例代碼:
<!-- 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>
對比兩段代碼,不難發(fā)現(xiàn),
label與input標簽的包含關系不同。Code 1 的label和input,屬于包含關系,Code 2 的label和input相對獨立。
label與input在頁面上的排列方式不同。通過Chrome的開發(fā)者工具不難發(fā)現(xiàn),Code 1 的運行結(jié)果,label標簽將input標簽遮蓋,Code 2 的運行結(jié)果,label標簽與input標簽并列。
label與input一一對應。點擊label的內(nèi)容,對應的單端按鈕都會被選中。
如果,我們將兩段代碼中l(wèi)abel的for屬性刪除,則之前的第1點和第2點不變,變化的是第3點。Code 1 的運營結(jié)果,點擊label的內(nèi)容,照舊能夠選中單選按鈕。而 Code 2 的則不同,點擊label的內(nèi)容,無法選中單選按鈕。
經(jīng)過簡單的代碼運行結(jié)果對比,我們能夠驗證文章開頭引用的那段話是正確的。為label添加for屬性的這個做法,能夠提高代碼質(zhì)量。
相關文章推薦:
html中標簽嵌套的問題如何解決
父元素<a>標簽的默認行為以及click事件之間的相互影響
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com