jQuery获取最接近元素的div

时间:2018-11-18 20:27:59

标签: jquery

我正在尝试使用此jquery显示最接近select元素的div:

$(document).ready(function(e) {
    $('.destination_number').hide();
    $('.destination_select').each(function() {
        update_destination($(this));
    });
    $('.destination_select').on('change', function() {
        update_destination($(this));
    });
});
function update_destination(el) {
    $( $('.destination_select').closest('.destination_number') ).show();
}

使用HTML:

<div class="row">
<div class="col-md-12">
   <div class="form-group">
   <label>On No Answer</label>
   <select name="destination_select" id="destination_select" class="form-control destination_select">
   </select>
   </div><!-- /.form-group -->
</div><!-- /.col -->
</div><!-- /.row -->

<span class="destination_number" id="test">
<div class="row">
<div class="col-md-12">
    <div class="form-group">
    <label id="destination_number_label">Forward To Number</label>
        <input type="text" name="destination_number" id="destination_number" class="form-control" />
    </div><!-- /.form-group -->
</div><!-- /.col -->
</div><!-- /.row -->
</span>

但是它没有显示.destination_number div

会有多个div和具有相同类的select元素,我想显示最接近.destination_number元素的.destination_select div

更新

                <div class="row">
                <span class="destination_container">
                <div class="col-md-6">
                    <div class="form-group">
                    <label>On No Answer</label>
                    <select name="destination_select" class="form-control destination_select">
                    </select>
                    </div><!-- /.form-group -->
                </div><!-- /.col -->
                </span>

                <span class="destination_number">
                <div class="col-md-6">
                    <div class="form-group">
                    <label class="destination_number_label">Destination</label>
                    <input type="text" name="destination_number" class="form-control" value="<?php echo (isset($extension["dnumber"]) ? $extension["dnumber"] : (isset($_POST["destination_number"]) ? $_POST["destination_number"] : '')); ?>" />
                    </div><!-- /.form-group -->
                </div><!-- /.col -->
                </span>
                </div><!-- /.row -->

添加了内部函数:el.closest('.destination_number').next('.destination_number_label').text( $(el).find(':selected').attr('data-label') );

1 个答案:

答案 0 :(得分:1)

closest()仅查找祖先,而您要查找的不是<select>的祖先

您需要上移至最接近的行,然后查找下一个兄弟姐妹

function update_destination(el) {
    el.closest('.row').next('.destination_number') ).show();
}