html - 将表单字段放在标签标签内是好主意还是坏主意?

标签 html forms dom label standards

我在很多框架、自动生成的代码 (Zend) 和布局模板中注意到了这种趋势。我所说的方法是这样的:

<label for="someField">
    <input id="someField" name="someName" />
</label>

与常规方法相比,这种方法有哪些优点和缺点?为什么人们倾向于采用这种方法?

最佳答案

通过 W3C standards判断似乎没问题 在 HTML4.01 和 HTML5 中:

HTML4:

"To associate a label with another control implicitly, the control element must be within the contents of the LABEL element. In this case, the LABEL may only contain one control element. The label itself may be positioned before or after the associated control."

在此示例中,我们隐式地将标签与文本输入控件关联起来:

<form action="..." method="post">
  <p>
    <label>
      First Name
      <input type="text" name="firstname">
    </label>
  </p>
</form>

HTML5 开始仍然没问题:

"The label element represents a caption in a user interface. The caption can be associated with a specific form control, known as the label element's labeled control, either using the for attribute, or by putting the form control inside the label element itself. - W3C.

关于html - 将表单字段放在标签标签内是好主意还是坏主意?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15627050/

相关文章:

html - 有没有办法让 &lt;input&gt; 字段不可编辑

html - 视频源类型标签是可选的吗?如果是我应该将 src 内联而不是嵌套吗?

html - 无法在标题的同一行中获取 Logo 和导航栏

angular - 为什么我得到这些错误 "No value accessor for form control with path: ' rowDetails -> 0 -> no'”

java - 无法从表单操作调用 servlet

带有 recaptcha 的 PHP 表单

javascript - 使用 JavaScript 将子节点添加到内联 SVG。在 IE9 上不可能?

javascript - 如何使用虚拟 DOM 在 React/Javascript 中重新加载输入值?

javascript - <select> 元素并观察 ('click' ) 选项切换 option.selected

html - CSS & HTML 移动元素