为什么 HTML 元素(input、textarea 和 select)应该有关联的标签?

Why should HTML elements (input, textarea, and select) have associated labels?

任何人都可以阐明为什么(inputtextareaselect)应该有关联标签吗?

我找到了一个 Whosebug 线程 (Should I put input elements inside a label element?),它解释了关联 <input><label> 的所有方式,但我没有找到任何明确的解释为什么标签必须被关联。

例子

WebStorm (IDE) 针对此代码中的输入生成“缺少相关标签”警告:

<div>
  <input type="text" id="search" name="search">
  <button id="logout" name="logout">Logout</button>
</div>

应用自动更正为输入添加标签:

<div>
  <label>
    <input type="text" id="search" name="search">
  </label>
  <button id="logout" name="logout">Logout</button>
</div>

HTML没有标签也能正常工作,那我为什么要添加它呢?

关联标签用于辅助功能。因此,例如,当您 运行 在网站上检查 lightouse Chrome 时,它会在其报告的“辅助功能”部分指出缺少的标签。原因:

“标签可确保表单控件通过辅助技术(如屏幕 readers)正确显示”。

因此,当您的网站可供无法正确阅读或查看内容且需要屏幕的残障人士访问时,最好使用它们 reader。