使用 Jquery 找不到最近的标签



我找不到最接近的Jquery标签。

标签的 id 与输入的 id 不同:

$(document).delegate("input[type=text]", "keyup", function() {
  if (this.className == 'other-val') {
    $label = $('label[for="' + this.id + '"]');
    if ($label.length > 0) {
      console.log('ok')
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="radio-group-1548153603981-other">Other
    <input type="text" id="radio-group-1548153603981-other-value" class="other-val user-success" style="display: inline-block;">
    </label>

希望有人能帮助我

由于此元素有多个类名,因此必须使用 includes 而不是运算符=

此外,输入的 ID 是radio-group-1548153603981-other-value的,您错过了标签中的单词value,并且由于您的 HTML 是由第三方软件生成的,所以我使用 .replace 从输入 ID 中省略 -value

$(document).delegate( "input[type=text]", "keyup", function() {
        if(this.className.includes('other-val')){
            $label = $('label[for="'+ this.id.replace("-value","") +'"]');
            if ($label.length > 0 ) {
                console.log('ok')
            }
        }
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="radio-group-1548153603981-other">Other
<input type="text" id="radio-group-1548153603981-other-value" class="other-val user-success" style="display: inline-block;">
</label>

使用

on 而不是 delegate ,使用大多数 jQuery 功能,如果使用 jQuery,请不要组合纯 DOM javascript。

我看到标签是input的父级,所以使用最接近的方法。

$(document).on( "keyup", "input[type='text']", function() {
   if($(this).hasClass('other-val')) {
        $label = $(this).closest("label"); 
        if ($label.length > 0 ) {
            console.log('ok')
        }
    }
});
<label for="radio-group-1548153603981-other">

使用 jquery 获取上述标签的可能方法。

  1. $('label[for$=other]'); - "$="忽略"其他"之前的所有文本并找到控件
  2. $(this).siblings('label[for$=other]'); - 在其任何同级元素的回调函数内时。
  3. $('label[for=radio-group-1548153603981-other]')

你的标记有点让我感到困惑。 试试这个:

HTML 标记的示例:

<div>
  <label>some text</label>
  <input type="text">
</div>

Jquery 选择器:

let $input = $('input[type="text"]');
let $label = $input.parent().find('label');

标签不必包围输入字段