Html 将标签与输入相关联,而不是 id?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11830898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Associate label to input with class not id?
提问by Evanss
I know that you can associate a label with an input using the for and id attributes. However can you use a class and not an id? Thanks
我知道您可以使用 for 和 id 属性将标签与输入相关联。但是,您可以使用类而不是 id 吗?谢谢
<label for="rooms">Number of rooms</label>
<select id="rooms">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
回答by Madara's Ghost
Classes are not unique (you can have multiple elements with the same class), so no.
类不是唯一的(同一个类可以有多个元素),所以不是。
If you want to associate a label to an input without using ID, you can implicitlyassign it by including said input inside of the label:
如果您想在不使用 ID 的情况下将标签与输入相关联,您可以通过在标签内包含所述输入来隐式分配它:
<label>Number of rooms
<select name="rooms">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</label>
回答by Chris Troutner
Here is an example of when you wouldn't want to use an ID or nest the control:
以下是您不想使用 ID 或嵌套控件的示例:
I'm creating a BackboneJS application that uses templates. Because the template can be duplicated, it's important to refrain from using IDs, as it will create multiple elements in the DOM with the same ID.
I'm also using Bootstrap, which will present the control in a different (and undesirable) way if it's wrapped inside the
<label>
element.
我正在创建一个使用模板的 BackboneJS 应用程序。因为模板可以复制,所以不要使用 ID 很重要,因为它会在 DOM 中创建多个具有相同 ID 的元素。
我也在使用 Bootstrap,如果它被包裹在
<label>
元素中,它将以不同的(和不受欢迎的)方式呈现控件。
At this point, the only solution I can find is to wrap the control element and tweek the default CSS to get the desired output. If someone has a more elegant solution, please chime in.
在这一点上,我能找到的唯一解决方案是包装控制元素并调整默认 CSS 以获得所需的输出。如果有人有更优雅的解决方案,请加入。
回答by freefaller
No, you cannot use the class
of an element, because the same class can be used by multiple elements - in which case, which element would the label
be for?
不,您不能使用class
元素的 ,因为多个元素可以使用同一个类 - 在这种情况下,哪个元素将label
用于?
回答by Quentin
No, you can't. The only attribute you can use is the id
attribute.
不,你不能。您可以使用的唯一属性是id
属性。
It doesn't make sense to use a class (which describes a groupof related elements) since a label can be associated only with exactly one form control.
使用类(描述一组相关元素)是没有意义的,因为标签只能与一个表单控件相关联。