Asp.net-Mvc-3

驗證 HTML 時出錯:標籤元素的 for 屬性必須引用表單控制項

  • July 19, 2012

我不知道為什麼在http://validator.w3.org/check檢查我的頁面時不斷收到此錯誤 錯誤是:

Line 46, Column 68: The for attribute of the label element must refer to a form control. 
<label class="environment-label" for="environment_form">Environments:</label>

我相信我為我label的外部表單提供了一個 id 參考,為什麼它一直在困擾我這個錯誤?

<div>
   <form id="environment_form" method="post">
       <div class="styled-select">
           <label class="environment-label" for="environment_form">Environments:</label>
           <select name="environment_dropdown" onchange="selectionChanged()">
               <option @(ViewData["selection"] == null || string.IsNullOrEmpty(ViewData["selection"].ToString()) ? "selected" : "")>select one</option>
               @foreach (string name in Model) { 
                   <option @(ViewData["selection"] != null && ViewData["selection"].Equals(name) ? "selected" : "")> 
                       @name
                   </option>
               }
           </select> 
       </div>
   </form>
</div>

你有這個:

for="environment_form"

它直接引用表格!但是“for”屬性應該引用表單的一個元素,在您的情況下是選擇。因此,在您的選擇中添加一個“id”屬性並更改“for”,如下例所示:

<label class="environment-label" for="environment_dropdown">Environments:</label>
<select name="environment_dropdown" id="environment_dropdown" onchange="selectionChanged()">

引用自:https://stackoverflow.com/questions/11567494