html - 为什么 label 元素有一个 form 属性?

标签 html forms

在 HTML 标准中,为什么 HTML label 元素有一个 form当它已经具有 for 属性时为其定义属性?它有什么用途?

如果我有一个标签元素,其中子内容是输入类型或使用了 for 属性,那么 form 属性有什么用途?

例如,在下面的每个 label 场景中,通过查看子元素或父元素可以知道“拥有表单”。是否还有另一种情况,其中带有 form 属性的 label 既有用又不会增加困惑?

<body>
<form action="#" id="form-one" method="post">
    <label>Dog name<input type="text" id="tb-dog-name"></label>
    <button type="submit" id="form-one-submit">Post Dog Name</button>
</form>

<form action="#" id="form-two" method="post">
    <label for="tb-cat-name">Cat name</label>
    <input type="text" id="text-box-two">
    <button type="submit" id="form-two-submit">Post Cat Name</button>
</form>

<label for="tb-pizza">How much do you like pizza?</label>
<input type="text" id="tb-pizza" form="form-three">
<form action="#" id="form-three" method="post">
    <button type="submit" id="form-three-submit">Share your love!</button>
</form>

</body>

最佳答案

作为MDN状态:

form (HTML5) The form element that the label element is associated with (its form owner). The value of the attribute must be an ID of a element in the same document. If this attribute is not specified, this element must be a descendant of a element. This attribute enables you to place label elements anywhere within a document, not just as descendants of their form elements.

Additionally :表单关联元素(按钮字段集输入keygen标签对象输出选择textarea img)默认情况下与其最近的祖先表单元素相关联(如下所述),但是,如果它是可重新关联的(按钮字段集输入keygen标签对象输出select textarea), 可能指定了一个 form 属性来覆盖它。

关于html - 为什么 label 元素有一个 form 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23764963/

相关文章:

jquery - 使用表单编辑文本区域

forms - Wicket:模态窗口中的表单

html - Bootstrap 4 模态对齐问题

html - 为什么 Doctype 声明分为两行?

html - 通过向右浮动对齐 Div

c# - 如何以编程方式为单个应用程序设置多个身份验证 cookie

javascript - 如何绑定(bind)到复选框选中事件

html - anchor 在 div 内部不起作用,但它在 div 之上工作

javascript - 如何根据下拉菜单隐藏输入

javascript - 提交后更改 jQuery 选项卡