jQuery - 选择输入字段的关联标签元素 [英] jQuery - select the associated label element of a input field

查看:138
本文介绍了jQuery - 选择输入字段的关联标签元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < label for = 

我有一组输入字段,其中一些与标签关联, BLA > BLA< /标签> < input type =textid =bla/>

< label for =foo> bla< input type =checkboxid =foo/> < /标签>

< input ... />

那么,如何为每个输入选择相关的标签(如果存在)?

解决方案

你不应该依赖于使用 prev 。只需使用作为标签的属性,因为它应该对应于您当前操作的元素的ID:

  var label = $(label [for ='+ $(this).attr('id')+']); 

然而,有些情况下标签的 code> set,在这种情况下,该标签将是其关联控件的父项。要在两种情况下找到它,可以使用以下变体:

  var label = $('label [for =  '+ $(本).attr(' ID ')+']');如果(label.length< = 0){
var parentElem = $(this).parent(),
parentTagName = parentElem.get(0).tagName,

。 toLowerCase();

if(parentTagName ==label){
label = parentElem;
}
}

我希望这有助于您!


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?

解决方案

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:

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:

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!

这篇关于jQuery - 选择输入字段的关联标签元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆