Javascript 在div中查找具有特定类的最近跨度

Javascript 在div中查找具有特定类的最近跨度,javascript,jquery,html,Javascript,Jquery,Html,我想找到最接近的span类error\u span。如何使用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">

我想找到最接近的
span
error\u span
。如何使用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>
我的jquery函数在这里

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
是父元素的子元素,该父元素是
输入的同级元素

要解决您的问题,请遍历
输入
span
的一个公共父项,然后从那里使用
find()
。试试这个:

$("#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");
    }
}

最近的父母还是孩子?和最接近哪个元素?最接近哪个元素?最接近哪个元素?假设您想获取输入的跨度
$(this).parent()。最接近('div')。查找('error_span')
到目前为止您尝试了什么?谢谢它工作得很好。最后一个问题是,如果div和class form group中有其他span,我的函数是否有效?如果您有多个
.form group
类的元素,它仍然有效,但它会在这两个元素上设置文本和类我的过程是否正常?在我传递元素id的函数中,它只会找到最近的.form组类吗?
$("#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");
    }
}