Javascript jQuery - 选择输入字段的关联标签元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4844594/
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
jQuery - select the associated label element of a input field
提问by Alex
I have a set of input fields, some of them have labels associated, some not:
我有一组输入字段,其中一些有关联的标签,有些没有:
<label for="bla">bla</label> <input type="text" id="bla" />
<label for="foo">bla <input type="checkbox" id="foo" /> </label>
<input ... />
so, how can I select the associated label for each input, if it exists?
那么,如何为每个输入选择关联的标签(如果存在)?
回答by jgradim
You shouldn't rely on the order of elements by using prev
or next
. Just use the for
attribute of the label, as it should correspond to the ID of the element you're currently manipulating:
您不应该使用prev
或 来依赖元素的顺序next
。只需使用for
标签的属性,因为它应该对应于您当前正在操作的元素的 ID:
var label = $("label[for='" + $(this).attr('id') + "']");
However, there are some cases where the label will not have for
set, in which case the label will be the parent of its associated control. To find it in both cases, you can use a variation of the following:
但是,在某些情况下标签没有for
设置,在这种情况下标签将是其关联控件的父级。要在这两种情况下找到它,您可以使用以下变体:
var label = $('label[for="' + $(this).attr('id') + '"]');
if(label.length <= 0) {
var parentElem = $(this).parent(),
parentTagName = parentElem.get(0).tagName.toLowerCase();
if(parentTagName == "label") {
label = parentElem;
}
}
I hope this helps!
我希望这有帮助!
回答by Maxim Kulkin
There are two ways to specify label for element:
有两种方法可以为元素指定标签:
- Setting label's "for" attribute to element's id
- Placing element inside label
- 将标签的“for”属性设置为元素的 id
- 在标签内放置元素
So, the proper way to find element's label is
所以,找到元素标签的正确方法是
var $element = $( ... )
var $label = $("label[for='"+$element.attr('id')+"']")
if ($label.length == 0) {
$label = $element.closest('label')
}
if ($label.length == 0) {
// label wasn't found
} else {
// label was found
}
回答by Nathan Anderson
As long and your input
and label
elements are associated by their id
and for
attributes, you should be able to do something like this:
只要你的input
andlabel
元素通过它们的id
andfor
属性关联,你应该能够做这样的事情:
$('.input').each(function() {
$this = $(this);
$label = $('label[for="'+ $this.attr('id') +'"]');
if ($label.length > 0 ) {
//this input has a label associated with it, lets do something!
}
});
If for
is not set then the elements have no semantic relation to each other anyway, and there is no benefit to using the label tag in that instance, so hopefully you will always have that relationship defined.
如果for
未设置,则元素之间无论如何都没有语义关系,并且在该实例中使用标签标签没有任何好处,因此希望您始终定义该关系。