jquery - 使用 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 是由第三方软件生成的,所以我使用从输入 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>
推荐阅读
- powerbi - 如何在新度量中获取度量(日期)之前每个实体的最后一个分数
- ionic-framework - 离子代码 3、4 TypeError 中的承诺错误:无法读取未定义的属性“nomeCategoria”
- ios - 循环将在 Objective-C 中最多运行一次(循环增量从未执行)
- angular - 如何从指令访问 FormGroup - Thinbug
- javascript - 从另一个文件中的一个 JS 文件调用变量
- javascript - 如何在百度的echarts中为SingleAxis上的所有轴设置Datazoom?
- corda - 如何在 R3 Corda 上使帐户处于非活动状态
- java - 解码图像的所有可能方法
- r - 如何估算 NA 依赖于另一个预测变量?
- javascript - 如何在 js 图表中抓取数据