在div中查找与特定类最接近的跨度 [英] Finding the closest span with a specific class inside a div
本文介绍了在div中查找与特定类最接近的跨度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想找到最接近类error_span
的span
.如何使用jQuery做到这一点?
I want to find the closest span
with class error_span
. How can I do that using jQuery?
<div class="form-group row">
<div class="col-sm-4">
<label for="reimburse_price" class="control label">Amount</label>
</div>
<div class="col-sm-8">
<div>
<input type="text" name="reimburse_price" min="1" placeholder='0.00' class="form-control numberOnly" id="reimburse_price" required>
</div>
<div>
<span class="small text-danger error_span"></span>
</div>
</div>
</div>
我的JavaScript在这里
My javascript is here
$("#reimburse_price").blur(function(){
checkNumInput("#reimburse_price");
});
我的jquery函数在这里
My jquery function is here
function checkNumInput(id){
if ($(id).val() == "") {
$(id)[0].setCustomValidity('Please fill out this field');
$(id).closest("span .error_span").text("Please fill out this field").removeClass("hidden").addClass("text-danger");
}
}
推荐答案
当前代码的问题是closest()
查看父元素,而您要查找的span
是父元素的子元素. input
.
The issue with your current code is that closest()
looks at parent elements, yet the span
you want to find is a child of a parent's sibling to the input
.
要解决您的问题,请遍历input
和span
的公共父级,然后从此处使用find()
.试试这个:
To solve your issue traverse to a common parent of both the input
and span
and use find()
from there. Try this:
$("#reimburse_price").blur(function() {
checkNumInput('#' + this.id);
});
function checkNumInput(id) {
var $input = $(id);
if ($input.val() == "") {
$input.get(0).setCustomValidity('Please fill out this field');
$input.closest('.form-group').find('.error_span').text("Please fill out this field").toggleClass("hidden text-danger");
}
}
这篇关于在div中查找与特定类最接近的跨度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文