我正在尝试获取所选菜单值以显示内容。当我尝试选择值$(this).find('select[id^="requirement_type_]:selected').val();
时,我得到了undefined
。
根据这个值,我想要对应的id
div到d-none
的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>
1条答案
按热度按时间eqzww0vc1#
:selected
伪类属于所选的option
,而不是整个select
元素。但你不需要它,你可以只获取select
的值来获取其所选选项的值。如果使用类而不是ID前缀,则会更简单、更有效。
那么你可以用