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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:22:01  来源:igfitidea点击:

jQuery - select the associated label element of a input field

javascriptjqueryforms

提问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 prevor next. Just use the forattribute 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 forset, 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:

有两种方法可以为元素指定标签:

  1. Setting label's "for" attribute to element's id
  2. Placing element inside label
  1. 将标签的“for”属性设置为元素的 id
  2. 在标签内放置元素

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 inputand labelelements are associated by their idand forattributes, you should be able to do something like this:

只要你的inputandlabel元素通过它们的idandfor属性关联,你应该能够做这样的事情:

$('.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 foris 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未设置,则元素之间无论如何都没有语义关系,并且在该实例中使用标签标签没有任何好处,因此希望您始终定义该关系。