Jquery显示隐藏后无法处理选择选项



考虑以下引导程序选择选择器:

<select id="parent" class="selectpicker">
<option value="1">Parent 1</option>
<option value="2">Parent 2</option>
</select>
<select id="child" class="selectpicker">
<option value="1">Child - Parent 1</option>
<option value="2">Child - Parent 2</option>
</select>
$("#parent").on('change', function (e) { 
var parentId = $(this).val();
$("#child option").each((i,a) => {
var childParentId = $(a).value();
if(childParentId != parentId) {
$(a).hide();
} else { $(a).show() }
});
$("#child").selectpicker("refresh")
});

不管我做什么,$(a(.show((都没有效果。我缺少什么?

您需要使用$(this)来获取dom,而不是$(a)

更新:jsfiddle

$("#parent").on('change', function (e) { 
var parentId = $(this).val();
$("#child option").each(function() {
var childParentId =  $(this).val();
if(childParentId != parentId) {
$(this).hide();
} else { $(this).show() }
});
// $("#child").selectpicker("refresh")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="parent" class="selectpicker">
<option value="1">Parent 1</option>
<option value="2">Parent 2</option>
</select>
<select id="child" class="selectpicker">
<option value="1">Child - Parent 1</option>
<option value="2">Child - Parent 2</option>
</select>

问题出在这一行

var childParentId = $(a).value();

如果使用value(),正确的语法是val()

最新更新