我试图获得所选菜单值来显示内容。当我尝试选择值$(this).find('select[id^="requirement_type_]:selected').val();
时,我得到的是undefined
。
根据该值,我希望d-none
的id
div对应于removeClass
:
$( document ).ready(function() {
$( 'div[id^="requirement_row"]' ).each(function( i ) {
// requirement_row[{$row_number}]
var req_parent_div_id = this.id;
// get row id inside brackets
var req_row_id_matches = req_parent_div_id.match(/[(.*?)]/);
var req_row_id = req_row_id_matches[0];
// get the rquirement type (training / certification)
var req_type = $(this).find('select[id^="requirement_type_]:selected').val();
console.log(req_type);
// remove 'd-none' from selected requirement type
// $('#' + 'requirement_' + req_type + '[' + req_row_id + ']').removeClass('d-none');
// remove 'd-none' class to show the requirement row
$(this).removeClass('d-none');
});
});
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d-none" id="requirement_row[0]">
<div>
<select id="requirement_type_0">
<option value="training">Training</option>
<option value="certification" selected>Certification</option>
</select>
</div>
<div class="d-none" id="requirement_training[0]">
training
</div>
<div class="d-none" id="requirement_certificationg[0]">
certification
</div>
</div>
<div class="d-none" id="requirement_row[1]">
<div>
<select id="requirement_type_1">
<option value="training" selected>Training</option>
<option value="certification">Certification</option>
</select>
</div>
<div class="d-none" id="requirement_training[1]">
training
</div>
<div class="d-none" id="requirement_certificationg[1]">
certification
</div>
</div>
:selected
伪类属于被选中的option
,而不是整个select
元素。但是您不需要它,您可以获取select
的值来获取其所选选项的值。
$(this).find('select[id^="requirement_type_]').val()
如果使用类而不是ID前缀,会更简单、更有效。
<select id="requirement_type_1" class="requirement_type">
那么你可以使用
$(this).find(".requirement_type").val()