首页 > 解决方案 > 使用 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>

希望有人可以帮助我

标签: jquery

解决方案


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

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


推荐阅读